Explain computing tree height.
Skip to solutionKEEP THE
easyDSA
How do you find the maximum depth of a binary tree?
89 views
01
Understand the problem
treesrecursion
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Recurse: depth of a node = 1 + max(depth(left), depth(right)), with null nodes contributing 0. It visits each node once — O(n) time, O(h) stack space. A BFS level count gives the same answer iteratively.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Recursive height
Run Playgroundclass TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_depth(root):
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
# --- demo --- tree of depth 3
root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(max_depth(root)) # 305
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 26 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.