Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in Kotlin: Recursive DFS in 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 null.

 

Example 1:

      8
     / \
    4   -2
   /
  5
   \
    1

Input: root = [8,4,-2,5,null,null,null,null,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

    KOTLIN · BINARY TREES

    Maximum Depth Of Binary Tree in Kotlin, explained

    Problem overview

    maxDepth receives the root of a binary tree, a TreeNode?, and returns its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree, where root is null, has depth 0.

    The lesson provides the node class: a TreeNode has an Int field value and two nullable children, left and right.

    For the tree [3,9,20,null,null,15,7] the root 3 has a left child 9 and a right child 20, and 20 has children 15 and 7. The longest paths, 3 -> 20 -> 15 and 3 -> 20 -> 7, have 3 nodes, so the answer is 3. For [1,null,2] it is 2, and for the empty tree it is 0.

    Approach

    A tree is one node deeper than the deeper of its two subtrees. The root adds one level, and below it the longest path goes through the left or the right child, whichever is deeper. A subtree is itself a binary tree, so the same function can compute its depth. That is recursion.

    A recursive function needs a base case that stops it. Here it is the empty tree, null, whose depth is 0. A leaf has two null children, so it gets 1 + max(0, 0) = 1.

    Each node is visited once, so the time is O(n) for n nodes.

    Step by step

    1. Handle the empty tree. If root == null, return 0. This check also stops the recursion when it steps past a leaf.
    2. Find the left depth. Call maxDepth(root.left) and keep the result in leftDepth. Trust the call to return the depth of the left subtree, whatever its shape.
    3. Find the right depth the same way, with root.right. A missing child gives 0 thanks to the base case.
    4. Combine. Return 1 + maxOf(leftDepth, rightDepth): the root itself plus the longest path below it.

    The solution in Kotlin

    class Solution {
        fun maxDepth(root: TreeNode?): Int {
            if (root == null) {
                return 0
            }
            val leftDepth = maxDepth(root.left)
            val rightDepth = maxDepth(root.right)
            return 1 + maxOf(leftDepth, rightDepth)
        }
    }
    

    Some Kotlin details in this code:

    • The parameter type TreeNode? allows null. After the if (root == null) check that returns, Kotlin knows root is not null (a smart cast), so root.left is written without ?..
    • root.left and root.right are themselves nullable, which is why maxDepth takes a TreeNode?: the recursive calls can pass them directly.
    • maxOf(leftDepth, rightDepth) returns the larger of two Int values.
    • A method can call itself by name, here maxDepth, as long as its return type is declared, which it is.

    Tracing the first example

    Running the function on the example tree and on some of its subtrees gives:

    tree rooted at 3: 3
    subtree rooted at 9: 1
    subtree rooted at 20: 2
    

    The node 9 is a leaf, so its depth is 1. The node 20 has two leaf children, so its depth is 1 + max(1, 1) = 2. The root takes the larger of 1 and 2 and adds 1, which is 3.

    Complexity

    Time: O(n). Every node is visited exactly once, and each visit does constant work.

    Space: O(h), where h is the height of the tree. The recursion keeps one call open per level of the current path. For a balanced tree that is about log n, and for a tree that is a single chain it is n. The lesson's trees are at most 400 levels deep, which is a safe depth for recursion.

    Edge cases and common mistakes

    • Empty tree. null gives 0.
    • Single node. A tree with only a root gives 1.
    • A chain. [1,null,2] gives 2. A chain of 400 nodes, each the left child of the next, gives 400.
    • Returning the wrong base value. Depth counts nodes, not edges, so an empty tree is 0 and a leaf is 1. Returning 1 for null would make every answer too large by one.
    • Forgetting the 1 +. Without it the function returns 0 for every tree.
    • Using + instead of maxOf. Adding the two depths counts the nodes of both sides rather than the longest path.

    Testing

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