Maximum depth of binary tree shown with top-down and bottom-up DFS in Java, Python and Rust

LeetCode 104 Maximum Depth of Binary Tree – Java Python Rust

Day 34 of the Tekraze DSA series is Maximum Depth of Binary Tree, which is LeetCode 104. The answer is one line of code, and that is exactly why people get it wrong in interviews. They memorise the line without seeing what the recursion actually does. So today we slow it right down and dry run the tree step by step, once bottom up and once top down, and then look at the small mistakes that turn a correct answer of 3 into a wrong answer of 2.

What is the Maximum Depth of Binary Tree problem?

You are given the root of a binary tree. Return its maximum depth, which is the number of nodes along the longest path from the root down to the farthest leaf. An empty tree has depth 0 and a single node has depth 1.

Input:  root = [3, 9, 20, null, null, 15, 7]
Output: 3

      3          depth 1
     / \
    9   20       depth 2
       /  \
      15   7     depth 3

Input:  root = [1, null, 2]   Output: 2
Input:  root = []             Output: 0

The longest path here is 3, 20, 15 (or 3, 20, 7), which has three nodes, so the answer is 3. The tree can have up to 10,000 nodes. If the level order notation looks strange, the trees and graphs explained helper explains how trees are stored and drawn.

What is the difference between top down and bottom up DFS?

Both are depth first searches and both visit every node once. The difference is which way the information flows.

  • Bottom up. A node does not know its own depth. It asks its left and right children how deep they go, waits for both answers, takes the bigger one and adds 1 for itself. Information flows up from the leaves to the root.
  • Top down. A node is told its depth by its parent. It compares that number with the best depth seen so far, then tells each child that it sits one level deeper. Information flows down from the root to the leaves.

Bottom up returns a value from every call. Top down usually returns nothing and updates a shared answer instead. Once you can see both shapes, a lot of later tree problems become a question of which one fits.

How does the bottom up recursion run, step by step?

Here is the real trace from our test run on the example tree. Indentation shows how deep the call stack is, and calls on empty children return 0 without printing anything. Notice that no node can finish until both of its children have finished, so the leaves report first and the root reports last.

call maxDepth(3)
  call maxDepth(9)
  node 9: left=0, right=0, return 1 + max(0, 0) = 1
  call maxDepth(20)
    call maxDepth(15)
    node 15: left=0, right=0, return 1 + max(0, 0) = 1
    call maxDepth(7)
    node 7: left=0, right=0, return 1 + max(0, 0) = 1
  node 20: left=1, right=1, return 1 + max(1, 1) = 2
node 3: left=1, right=2, return 1 + max(1, 2) = 3
answer = 3

Read it from the bottom of the tree upwards. Each leaf sees two empty children worth 0 and reports 1. Node 20 hears 1 from both sides and reports 2. The root hears 1 from node 9 and 2 from node 20, keeps the 2, adds itself and returns 3. If the call stack itself still feels like magic, the recursion explained helper walks through it with pictures.

How does the top down recursion run, step by step?

Now the same tree with the top down version, where we pass the depth down and keep a running best. This is also the real output from the box.

visit 3  at depth 1, best 0 -> 1
visit 9  at depth 2, best 1 -> 2
visit 20 at depth 2, best 2 -> 2
visit 15 at depth 3, best 2 -> 3
visit 7  at depth 3, best 3 -> 3
answer = 3

This time the root is processed first, because it already knows it sits at depth 1. Every node simply checks whether it is the deepest one so far. Nothing is combined on the way back up, so the answer is ready the moment the last node is visited.

Which one should you use in an interview?

  • Use bottom up when the answer for a node depends on the answers of its subtrees. Maximum depth, balanced tree checks, diameter and subtree sums all fit this shape, and it gives the shortest code.
  • Use top down when a node needs something from above, such as its depth, the path so far or a running sum from the root. Path sum problems and right side view are natural fits.
  • For this problem both are correct and both are O(n). Write bottom up first because it is one line, then mention that the top down version gives the same answer if the interviewer asks for a different style.

What is the time and space complexity?

Each node is visited exactly once with constant work, so time is O(n) for both versions. Space is O(h) for the call stack, where h is the height of the tree. That is about log n for a balanced tree and n for a tree that is one long chain. If these terms feel fuzzy, the Big O helper post on time and space complexity explains them with simple examples.

What mistakes give the wrong depth?

We ran each of these on the example tree, where the right answer is 3. All three returned 2.

  • Counting edges instead of nodes. Returning -1 for an empty tree measures edges, so the example gives 2. LeetCode counts nodes, so an empty tree must return 0.
  • Starting top down at depth 0. If you call dfs(root, 0), every node is labelled one level too low and the answer comes out as 2. The root is depth 1.
  • Using min instead of max. Writing 1 + min(left, right) by accident returns 2 here, because node 9 has no children. Here that 2 happens to match the shallowest leaf, but on [1, null, 2] the same code returns 1 because it treats the missing left child as a leaf. Minimum depth is a separate problem with its own rules.
  • Calling the function twice per child. Something like maxDepth(left) > maxDepth(right) ? maxDepth(left) + 1 : maxDepth(right) + 1 gives the right answer but recomputes subtrees again and again, which can blow up on skewed trees. Store each result once.

Maximum Depth of Binary Tree in Java

import java.util.*;

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}

class Solution {
    // Bottom-up DFS: each node asks its children for their depth, then adds 1
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

    // Top-down DFS: carry the current depth down and record the deepest node seen
    private int best;

    public int maxDepthTopDown(TreeNode root) {
        best = 0;
        dfs(root, 1);
        return best;
    }

    private void dfs(TreeNode node, int depth) {
        if (node == null) return;
        best = Math.max(best, depth);
        dfs(node.left, depth + 1);
        dfs(node.right, depth + 1);
    }
}

The top down version keeps best as a field so the helper can update it. Reset it at the start of each call, otherwise a second test case would start from the old answer.

Maximum Depth of Binary Tree in Python

from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    # Bottom-up DFS: each node asks its children for their depth, then adds 1
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

    # Top-down DFS: carry the current depth down and record the deepest node seen
    def maxDepthTopDown(self, root: Optional[TreeNode]) -> int:
        best = 0

        def dfs(node, depth):
            nonlocal best
            if node is None:
                return
            best = max(best, depth)
            dfs(node.left, depth + 1)
            dfs(node.right, depth + 1)

        dfs(root, 1)
        return best

In Python the inner dfs needs nonlocal best to update the outer variable. Without it Python treats best as a new local name and raises an error.

Maximum Depth of Binary Tree in Rust

use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    pub fn new(val: i32) -> Self {
        TreeNode { val, left: None, right: None }
    }
}

struct Solution;

impl Solution {
    // Bottom-up DFS: each node asks its children for their depth, then adds 1
    pub fn max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        match root {
            None => 0,
            Some(node) => {
                let n = node.borrow();
                1 + Self::max_depth(n.left.clone()).max(Self::max_depth(n.right.clone()))
            }
        }
    }

    // Top-down DFS: carry the current depth down and record the deepest node seen
    pub fn max_depth_top_down(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        fn dfs(node: &Option<Rc<RefCell<TreeNode>>>, depth: i32, best: &mut i32) {
            if let Some(n) = node {
                let n = n.borrow();
                *best = (*best).max(depth);
                dfs(&n.left, depth + 1, best);
                dfs(&n.right, depth + 1, best);
            }
        }
        let mut best = 0;
        dfs(&root, 1, &mut best);
        best
    }
}

LeetCode uses Option<Rc<RefCell<TreeNode>>> for trees in Rust. The top down helper borrows each node and passes best as a mutable reference, so no global state is needed.

We ran all three languages on the box before writing this. Both versions were checked on [3, 9, 20, null, null, 15, 7], [1, null, 2], an empty tree, a single node, [1, 2, 3, 4, null, null, 5, 6] and a five level chain. Python also compared both versions with an independent level counting check on 200 random trees. Every test passed.

Which earlier posts in the series should you read?

If you are new here, start with Day 1, Two Sum and Day 2, Best Time to Buy and Sell Stock. Day 13, Valid Parentheses, Day 14, Min Stack and Day 15, Evaluate Reverse Polish Notation show how a stack works, which is exactly what the call stack is doing in today’s dry runs. Trees are linked nodes, so Day 18, Reverse Linked List and Day 19, Merge Two Sorted Lists are good warm ups. Day 23, Binary Search and Day 24, Search a 2D Matrix cover binary search, which comes back with binary search trees. For more binary search practice try Day 25, Koko Eating Bananas, Day 26, Find Minimum in Rotated Sorted Array, Day 27, Search in Rotated Sorted Array. The data structures cheat sheet is a handy one page summary.

Frequently asked questions

What is the maximum depth of a binary tree?

It is the number of nodes on the longest path from the root down to the farthest leaf. An empty tree has depth 0 and a tree with only a root has depth 1.

What is the difference between top down and bottom up recursion in trees?

Bottom up recursion asks the children for their answers and combines them on the way back up. Top down recursion passes information such as the current depth from the parent down to the children and updates a shared answer.

What is the time and space complexity of Maximum Depth of Binary Tree?

Time is O(n) because every node is visited once. Space is O(h) for the recursion stack, where h is the tree height, which is O(log n) for a balanced tree and O(n) for a skewed one.

Why does my maximum depth solution return one less than expected?

You are probably counting edges instead of nodes, either by returning -1 for an empty tree or by starting a top down search at depth 0. Return 0 for null and give the root depth 1.

Can you find the maximum depth without recursion?

Yes. A breadth first search with a queue counts levels one at a time, and the number of levels is the maximum depth. This avoids stack overflow on very deep trees.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×