Programming Interviews Exposed: Secrets to Landing Your Next Job, 3rd Edition
by John Mongan, Eric Giguere, Noah Kindler
Tree and Graph Problems
Most tree problems involve binary trees. You may occasionally encounter a graph problem, especially if the interviewer thinks you’re doing particularly well with easier problems.
Height of a Tree
Start by looking at some simple trees to see if there’s a way to think recursively about the problem. Each node in the tree corresponds to another subtree rooted at that node. For the tree in Figure 5-2, the heights of each subtree are:
- A: height 4
- B: height 1
- C: height 3
- D: height 2
- E: height 2
- F: height 1
- G: height 1
- H: height 1
Your initial guess might be that the height of a node is the sum of the height of its children because height A = 4 = height B + height C, but a quick test shows that this assumption is incorrect because height C = 3, but the heights of D and E add up to 4, not 3.
Look at the two subtrees on either side of a node. If you remove one of the subtrees, does the height of the tree change? Yes, but only if you remove the taller subtree. This is the key insight you need: The height of a tree equals the height of its tallest subtree plus one. This is a recursive definition that is easy to translate to code:
public static int treeHeight( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access