Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in Go: Recursion, O(n) Time

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

    GO · BINARY TREES

    Maximum Depth Of Binary Tree in Go, explained

    Problem overview

    The function maxDepth receives root, a pointer to the top node of a binary tree, and returns the tree's maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree, where root is nil, has depth 0. The lesson provides the TreeNode type, with an integer Val and two pointers, Left and Right, that are nil when a child is missing.

    For the tree with root 3, whose left child is 9 and whose right child is 20 with children 15 and 7, the answer is 3. The paths 3, 20, 15 and 3, 20, 7 have three nodes each, and the path 3, 9 has two. For a root 1 with a single right child 2 the answer is 2, and for an empty tree it is 0.

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

    Approach: one node deeper than the deeper subtree

    A tree is built from smaller trees. The depth of a tree with a root is 1 (the root itself) plus the depth of whichever subtree is deeper. The subtrees are trees too, and they follow the same rule, so the problem calls for recursion.

    Every recursion needs a base case, a case so small that the answer is known. Here it is the empty tree. A nil pointer has depth 0. This also covers missing children: stepping from a leaf to its nil child returns 0 and ends that branch.

    Each node is handled once, so the work is proportional to the number of nodes.

    Step by step

    1. Handle the empty tree. If root == nil, return 0. This is both the answer for an empty input and the stopping point for every branch of the recursion.
    2. Find the left depth. Call maxDepth(root.Left) and store it in leftDepth with :=. You don't need to know how the call works inside. It returns the depth of the smaller tree under the left child, whatever its shape.
    3. Find the right depth the same way with root.Right. A missing child gives 0, because of the base case.
    4. Combine. Return 1 plus the larger of the two depths. The 1 counts the root, and the larger depth is the longest path below it.

    The solution in Go

    func maxDepth(root *TreeNode) int {
    	if root == nil {
    		return 0
    	}
    	leftDepth := maxDepth(root.Left)
    	rightDepth := maxDepth(root.Right)
    	return 1 + max(leftDepth, rightDepth)
    }
    

    On the first example, the call for the root 3 asks for the depths of its subtrees. The subtree rooted at 9 has depth 1, because both of its children are nil. The subtree rooted at 20 has depth 2, and the call on the root returns 1 + max(1, 2), which is 3. Running the function on the three examples gives 3, 2 and 0.

    Go details

    • Reading a field of nil panics. The function checks root == nil before touching root.Left. Reading a field of a nil pointer panics, so without that check the recursion would crash at the first leaf.
    • Built-in max. Since Go 1.21, max is part of the language and works for numbers and strings. Before that, you had to write your own helper function.
    • Pointers need no dereferencing syntax. root.Left works on a *TreeNode directly; Go follows the pointer for you.
    • Recursion depth. Go grows a goroutine's stack as needed, so a chain of 100,000 nodes still returns 100000. The lesson's trees have at most 400 levels, which is no problem.

    Complexity

    Time: O(n). Each node is visited by exactly one call, and each call does a fixed amount of work besides its two recursive calls. The nil children add at most n + 1 further calls that return at once.

    Space: O(h), where h is the tree's height. The recursion keeps one frame per level of the path being explored, so a balanced tree uses about log n frames and a chain uses n. The function creates no data structures of its own.

    Edge cases and common mistakes

    • Empty tree. maxDepth(nil) returns 0.
    • A single node. Both children are nil, so the result is 1 + max(0, 0), which is 1.
    • A chain. A tree where every node has only a left child, with four nodes, has depth 4. The shallow side of each node contributes 0 and the deep side decides.
    • Counting edges instead of nodes. This problem counts nodes, so a single node has depth 1, not 0.
    • Forgetting the 1 +. Without it the function always returns 0.
    • Using the smaller depth, or adding the two. The depth of a node is 1 plus the larger of the two subtree depths, not their sum.
    • Skipping the nil check and then reading root.Left on an empty tree, which panics.

    Testing

    • [3, 9, 20, nil, nil, 15, 7] gives 3.
    • [1, nil, 2] gives 2.
    • [] gives 0.
    • A single node gives 1.
    • A chain of four nodes, each the left child of the one above, gives 4.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free