How will you find the depth of a binary tree?
💡Strategies for Solving This Problem
Easier Than It Sounds
This is usually a warm-up question. I've seen it at Google, Microsoft, and smaller companies. Don't overthink it.
What They're Testing
Can you think recursively? That's it. Binary tree problems are all about recursion or level-order traversal.
Approach 1: Recursive (The Standard Answer)
The depth of a tree is: 1 + max(depth of left, depth of right). This screams recursion.
Base case: empty tree has depth 0. Recursive case: 1 + deeper subtree.
This is what 90% of people use and what interviewers expect.
Approach 2: Iterative (BFS)
Use a queue and do level-order traversal. Count how many levels you process. More code, same result.
Only use this if:
- Interviewer specifically asks for iterative
- You're worried about stack overflow (very deep trees)
- You want to show you know BFS
Don't Do This
I once saw someone try to solve this iteratively with a stack (DFS). It works but requires tracking depths manually. Way more complex than needed.
Time Complexity
Both approaches: O(n) where n is number of nodes. You have to visit every node to know the max depth.
Quick tip: If interviewer says "find depth," start coding the recursive solution immediately. It's 5 lines.