← Trees

Max Depth Binary Tree

Easy
Python
def max_depth(root):
    if not root: return 0
    return 1+max(max_depth(root.left),max_depth(root.right))
Java
public int maxDepth(TreeNode root){
    if(root==null) return 0;
    return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}

Key Insight

'not root' works — None is falsy. max() vs Math.max().

Python → Java Differences

  • 'not root' vs root==null
  • max() vs Math.max()
  • Recursive DFS identical
Python
def max_depth(root):
    if not root: return 0
    return 1+max(max_depth(root.left),max_depth(root.right))
Java
public int maxDepth(TreeNode root){
    if(root==null) return 0;
    return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}

Algorithm Steps

1. Null: return 0
2. Return 1+max(depths)