Easy · Depth-First Search
Understand → Visualise → Practice.
Most tree problems become simple when you trust a function to solve the same problem for each subtree.
The depth of a tree is 1 plus the larger depth of its two subtrees. An empty tree has depth 0.
No node → depth 0.
Get the depth of left and right.
Return 1 + max(left, right).
O(n) time. O(h) stack space, where h is the tree height (O(n) for a chain).
Very deep, chain-like trees can overflow the recursion stack; an iterative BFS avoids that.
Read the full guides first: Binary Trees and Traversals, Binary Search Trees, Graphs, BFS and DFS, Weighted Graphs, Dijkstra and Union–Find.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.