Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in Scala: 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 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

    SCALA · BINARY TREES

    Maximum Depth Of Binary Tree in Scala, explained

    Problem overview

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

    The lesson provides the node class. A TreeNode is created with a value, TreeNode(3), and has two fields, left and right, which hold the child nodes or null when a child is missing.

    For the tree with root 3, left child 9, and right child 20 whose children are 15 and 7, the answer is 3. The paths 3, 20, 15 and 3, 20, 7 each have three nodes, while 3, 9 has only two. A tree holding just the root 1 with a right child 2 has depth 2, and an empty tree has depth 0. The follow-up asks for O(n) time, visiting each node once.

    Approach: one node deeper than the deeper subtree

    A tree is built from smaller trees. The longest path from the root goes down through either the left child's subtree or the right child's subtree, and it takes whichever is deeper. So the depth of a tree is 1, for the root itself, plus the larger of the depths of its two subtrees.

    That sentence is already a recursive definition, and it only needs a base case. A missing child is an empty tree, and an empty tree has depth 0. This one rule also ends the recursion: every path of calls eventually steps past a leaf and reaches null.

    For the tree with root 3, the call on node 9 returns 1 plus the larger of 0 and 0. The call on node 20 returns 1 plus the larger of 1 and 1, which is 2. The root then returns 1 plus the larger of 1 and 2, which is 3.

    Step by step

    1. Handle the empty tree. If root == null, return 0. This is the base case, and it also covers every missing child below a leaf.
    2. Find the left depth. Call maxDepth on root.left and keep the result in a val named leftDepth. Trust the call to return the depth of the smaller tree, however it is shaped.
    3. Find the right depth the same way with root.right, stored in rightDepth. A missing child gives 0 here, thanks to the base case.
    4. Combine them. Return 1 plus math.max(leftDepth, rightDepth): the root, plus the longest path below it.

    The solution in Scala

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

    The Scala details worth a closer look:

    • Recursive methods need a result type. Scala can infer many return types, but not for a method that calls itself. The : Int in the signature is required.
    • null and ==. root == null is a safe test: in Scala == compares values, and it handles null on the left side without throwing an exception. The type TreeNode accepts null here because the lesson's fields are initialised with it.
    • return. The lesson uses return explicitly. In Scala the last expression of a block is already its value, so 1 + math.max(leftDepth, rightDepth) alone would do the same. The early return 0 is the one place where it is useful.
    • math.max. It takes two numbers of the same type and returns the larger. With two Ints it returns an Int.
    • val for results that don't change. leftDepth and rightDepth are assigned once, so val is the right choice over var.

    Complexity

    Time: O(n). The method is called once for every node, and once more for every missing child, which is at most n + 1 extra calls. Each call does a constant amount of work apart from its recursive calls.

    Space: O(h), where h is the height of the tree. The recursion goes as deep as the tree does, and each active call holds a stack frame. For a balanced tree that is about log n. For a tree where every node has only a left child, it is n. The lesson promises at most 400 levels, which the JVM handles easily: a chain of 10,000 nodes also works.

    Edge cases and common mistakes

    • An empty tree. maxDepth(null) returns 0.
    • A single node. Both children are null, so the result is 1 plus the larger of 0 and 0, which is 1.
    • A lopsided tree. A root with a left leaf and a right child that has its own right child gives 3, because the deeper side wins.
    • A line of nodes. A tree where each node has only a left child, 400 of them, returns 400. Taking the shorter side instead of the longer one with math.min would give 1 for a node with one missing child, which is wrong.
    • Forgetting the 1 +. Without it the method always returns 0.
    • Counting edges instead of nodes. The lesson counts nodes, so a single node has depth 1, not 0.
    • Dropping the base case. Without the null check, the first call that reaches a missing child fails with a NullPointerException when it reads root.left.

    Testing

    • Root 3 with children 9 and 20, where 20 has children 15 and 7, gives 3.
    • Root 1 with only a right child 2 gives 2.
    • An empty tree gives 0.
    • A single node gives 1.
    • Root 1 with a left child 2 and a right child 3 that has a right child 4 gives 3.
    • A chain of 400 left children gives 400, and a chain of 10,000 gives 10000.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free