Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in Rust: Recursion with match, O(n)

Practice O(n) Read the full explanation

You get the root of a binary tree. Return the depth of the tree.

The depth counts the nodes on the longest path from the root down to a leaf. A leaf is a node with no children. An empty tree has a depth of 0.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as None.

 

Example 1:

      8
     / \
    4   -2
   /
  5
   \
    1

Input: root = [8,4,-2,5,None,None,None,None,1]
Output: 4
Explanation: The longest way down is 8 → 4 → 5 → 1.
It has 4 nodes.
The way to the other leaf, 8 → -2, has only 2 nodes.

Example 2:

Input: root = [6]
Output: 1
Explanation: The root is also the only leaf.

Example 3:

Input: root = []
Output: 0
Explanation: The tree is empty.

 

Constraints:

  • 0 to 10,000 nodes.
  • Each value is from -100 to 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you find the depth in O(n) time for n nodes? Look at each node just once.
STEP 1 OF 6
    Ctrl + Enter to check

    RUST · BINARY TREES

    Maximum Depth Of Binary Tree in Rust, explained

    Problem overview

    The function max_depth receives the root of a binary tree, an Option<Box<TreeNode>>, and returns its maximum depth: the number of nodes on the longest path from the root down to the farthest leaf. An empty tree, where the root is None, has depth 0. The lesson provides TreeNode, whose left and right fields are each an Option<Box<TreeNode>>.

    For the tree [3, 9, 20, None, None, 15, 7] (level order, with None for a missing child), the root 3 has a left child 9 and a right child 20, and 20 has the children 15 and 7. The longest paths, 3 → 20 → 15 and 3 → 20 → 7, have 3 nodes, so the answer is 3. The path 3 → 9 has only 2. For [1, None, 2] the answer is 2, and for the empty tree it is 0.

    Approach: one more than the deeper child

    A tree is built from smaller trees, which suggests recursion. The depth of a tree is one node, the root, plus the longest path below it. The longest path below the root goes through one of the two children, so:

    depth(tree) = 1 + max(depth(left subtree), depth(right subtree))

    The recursion needs a place to stop. An empty tree has no nodes, so its depth is 0. This case also covers a missing child: a leaf has two empty children, and each answers 0, so a leaf has depth 1 + max(0, 0) = 1.

    Each node is visited once, so the time is O(n) for n nodes. The lesson's tree is at most 400 levels deep, so the recursion depth, and with it the stack, stays small.

    Step by step

    1. Match on root. The whole body is one match, with no semicolon after its closing brace, so the value of the match is the value of the function. Its arms handle the two shapes of an Option: no node, or a node.
    2. The base case. The arm None => 0 returns 0 for an empty tree. It also stops the recursion when it steps past a leaf.
    3. The node arm. Some(node) binds the box as node. Its body is a block, because it needs several lines. Inside it, node.left and node.right are the children, each an Option of its own.
    4. The left depth. Self::max_depth(node.left) is stored in left_depth. Trust the recursive call: it returns the depth of whatever tree hangs from the left child.
    5. The right depth. The same for node.right. A missing child gives 0 thanks to the base case.
    6. Combine. End the arm with 1 + left_depth.max(right_depth), with no semicolon: the node itself, plus the longest path below it.

    The solution in Rust

    impl Solution {
        fn max_depth(root: Option<Box<TreeNode>>) -> i32 {
            match root {
                None => 0,
                Some(node) => {
                    let left_depth = Self::max_depth(node.left);
                    let right_depth = Self::max_depth(node.right);
                    1 + left_depth.max(right_depth)
                }
            }
        }
    }
    

    The Rust details worth a closer look:

    • match is an expression. Each arm produces a value, and the value of the arm that runs becomes the value of the whole match. Because the match is the last thing in the function, it is the returned value, and no return is needed.
    • The compiler checks the cases. A match must cover every possibility, and the two arms None and Some(node) cover every Option. Leaving one out is a compile error, which removes the "forgot the empty tree" bug.
    • The tree is moved, not borrowed. The function takes root by value, and Self::max_depth(node.left) moves the left subtree into the call. This is fine because the function needs nothing from that subtree afterwards. Since node.left and node.right are separate fields, they can be moved out one after the other. The tree is consumed by the call, and the caller can't use it afterwards.
    • The Box. A struct can't contain itself directly, because its size would be infinite. A Box is a pointer to a node on the heap, which gives TreeNode a fixed size. Fields of a box are used as usual: node.left works on a Box<TreeNode> without any extra syntax.
    • Self::max_depth. The function has no self parameter, so the recursive call is written through Self::, which names the type the impl block belongs to.
    • max on integers. left_depth.max(right_depth) returns the larger of two values of the same type.

    Complexity

    Time: O(n). Each node gets exactly one call, plus one call for each missing child, so there are at most 2n + 1 calls, each doing a constant amount of work.

    Space: O(h), where h is the height of the tree, for the recursion stack. In a balanced tree this is about log n. In the worst case, a tree shaped like a line, it is n, and the lesson's limit of 400 levels keeps that safe.

    Edge cases and common mistakes

    • An empty tree. None matches the first arm and returns 0.
    • A single node. The tree [1] has depth 1: both children are None, so 1 + max(0, 0).
    • A line of nodes. [1, None, 2] has depth 2, and [1, 2, None, 3, None, 4], where every node has only a left child, has depth 4. The longer side is simply the one that exists.
    • Counting edges instead of nodes. The depth here counts nodes, so a single node is 1, not 0. The base case returning 0 for None, together with the 1 +, gives that.
    • Forgetting the 1 +. The function would return 0 for every tree, because it would only ever take the maximum of zeros.
    • Adding the depths instead of taking the larger. left_depth + right_depth measures the total, not the longest path.
    • A semicolon after the last expression. 1 + left_depth.max(right_depth); turns the arm's value into (), and the compiler reports a type mismatch.

    Testing

    • [3, 9, 20, None, None, 15, 7] gives 3.
    • [1, None, 2] gives 2.
    • [] gives 0.
    • [1] gives 1.
    • [1, 2, None, 3, None, 4] gives 4.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free