Tree DFS
Explore a tree recursively or with a stack, combining information from child subtrees.
The task asks about a root-to-leaf path, subtree property, height, diameter, or a recursive tree transformation.
How to approach it
Define precisely what each recursive call returns and handle the null node as the base case.
A recursive solution may use O(height) call stack and can overflow for a highly skewed tree in some runtimes.
Practice question
A binary tree has root 5, children 3 and 8, and node 3 has children 2 and 4. What is its maximum depth?
Levels: [5], [3, 8], [2, 4]Give your answer before revealing the explanation.Show a hint
Depth at a node is one plus the greater depth of its children.
Show an answer
3 nodes (levels) from root to deepest leaf.
Tree DFS at work
A company org chart is a tree. The root manager is at level 1, and the deepest employee is 5 reporting steps below. What is the chart's maximum depth in levels?
Show one possible approach
6 levels: the root level plus 5 edges below it. A DFS can return one plus the larger depth of the manager's child subtrees.
Practice next
Use these problem IDs to find additional practice for this pattern: