AceYourInterviews
Checking sign-in…

77. Maximum Depth of Binary Tree

FoundationTree depth with explicit DFS state

Find the greatest number of nodes on any path starting at the root and ending at a leaf. A leaf has no children.

Count nodes rather than edges. The empty tree has depth zero, while a tree containing only the root has depth one.

Example 1

Input

[3,9,20,null,null,15,7] in compact level order

Output

3

Explanation: The paths through node 20 to 15 or 7 contain three nodes.

Example 2

Input

[1,null,2,null,3] in compact level order

Output

3

Explanation: A skewed tree is still depth three; breadth and depth are different measures.

Constraints

  • 0 <= node count per tree <= 105
  • -231 <= node.value <= 231 - 1
  • Each input is a proper binary tree: no cycles or shared child nodes. Null trees are permitted.
Hints
Hint 1

What should null and a leaf return?

Hint 2

An explicit traversal needs to remember each node’s depth.

Hint 3

Start root at one, propagate depth+1, and retain the greatest visited depth.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Explicit depth frames

[3,9,20,null,null,15,7]
3