Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in Swift: O(n) Recursion

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 nil.

 

Example 1:

      8
     / \
    4   -2
   /
  5
   \
    1

Input: root = [8,4,-2,5,nil,nil,nil,nil,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 4
    Ctrl + Enter to check

    SWIFT · BINARY TREES

    Maximum Depth Of Binary Tree in Swift, explained

    Problem overview

    The method maxDepth(_ root: TreeNode?) receives the root of a binary tree 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 root is nil, has depth 0. The lesson provides the TreeNode class: each node has a val and optional left and right children.

    For the tree [3, 9, 20, nil, nil, 15, 7], written in level order with nil for a missing child, the answer is 3. The path 3 → 20 → 15 has three nodes, and so does 3 → 20 → 7, while 3 → 9 has only two. For [1, nil, 2] the answer is 2, and for the empty tree it is 0.

    The follow-up asks for O(n) time, visiting each of the n nodes once.

    Approach: a tree is one node deeper than its deeper subtree

    A binary tree is a node with two smaller binary trees under it, each possibly empty. That makes the depth easy to define in terms of itself: the depth of a tree is 1, for the root, plus the larger of the depths of its left and right subtrees. This is a natural fit for recursion.

    Every recursion needs a base case. Here it is the empty tree, whose depth is 0. A missing child is just a nil tree, so the base case also covers a leaf's two empty children and ends the recursion.

    Trace the first example. The depth of each node, from the bottom up, is:

    node 9:  1 + max(0, 0) = 1
    node 15: 1 + max(0, 0) = 1
    node 7:  1 + max(0, 0) = 1
    node 20: 1 + max(1, 1) = 2
    node 3:  1 + max(1, 2) = 3
    

    Each nil child returns 0, each leaf returns 1, and the answer, 3, comes out at the root. Every node is visited exactly once, which gives O(n) time.

    Step by step

    1. Handle the empty tree. Use guard let node = root else { return 0 }. This unwraps the optional into a constant node that is available for the rest of the function, and the else block runs when root is nil. The same check stops the recursion when it steps past a leaf.
    2. Find the left depth. Call maxDepth on node.left and store the result in leftDepth. Trust the call to return the depth of the smaller tree, whatever its shape.
    3. Find the right depth the same way, with node.right. A missing child gives 0 thanks to the base case.
    4. Combine them. Return 1 + max(leftDepth, rightDepth): this node itself, plus the longest path below it.

    The solution in Swift

    class Solution {
        func maxDepth(_ root: TreeNode?) -> Int {
            guard let node = root else {
                return 0
            }
            let leftDepth = maxDepth(node.left)
            let rightDepth = maxDepth(node.right)
            return 1 + max(leftDepth, rightDepth)
        }
    }
    

    The Swift details worth a closer look:

    • Optionals. The parameter is TreeNode?, so it can be nil. Writing root.left directly is a compile error: value of optional type 'TreeNode?' must be unwrapped to refer to member 'left' of wrapped base type 'TreeNode'. The guard let unwraps it once, and after that node is a plain TreeNode.
    • guard must leave the scope. The else block of a guard has to exit the function, for example with return. A block that just prints something is rejected with 'guard' body must not fall through, consider using a 'return' or 'throw' to exit the scope.
    • Recursive calls without self. Inside a method, maxDepth(node.left) calls the same method on the same Solution object, so no self. is needed.
    • max is a global function. max(leftDepth, rightDepth) returns the larger of two comparable values, here two Int values.
    • Child nodes are optionals too. node.left has the type TreeNode?, which is exactly what maxDepth accepts, so it can be passed on without unwrapping.

    Complexity

    Time: O(n). The function runs once for each of the n nodes and once for each missing child, which is at most n + 1 more calls. Each call does a constant amount of work.

    Space: O(h), where h is the height of the tree, for the recursion's call stack. The statement limits the tree to 400 levels, so the stack stays shallow. For a very unbalanced tree h can reach n, and a tree with a very large n could then exhaust the stack; a chain of 400 nodes is no problem.

    Edge cases and common mistakes

    • Empty tree. root = nil returns 0 from the guard.
    • A single node. Both children are empty and return 0, so the result is 1 + max(0, 0), which is 1.
    • A line of nodes. [1, nil, 2] has one child on the right and none on the left, so the result is 1 + max(0, 1), which is 2. A chain of 400 nodes, each the left child of the one above, gives 400.
    • Returning 1 for the empty tree. That adds one to every answer. The depth counts nodes, so no nodes means 0.
    • Adding the two depths. leftDepth + rightDepth is a different quantity: it is the length of a path that goes down both sides. The depth follows only the longer side, hence max.
    • Forgetting to add 1. Without the 1 +, the function returns 0 for every tree, since every path of recursion ends in a base case.

    Testing

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