In the Count Good Nodes in Binary Tree interview question, a node X in a binary tree is considered "good" if on the path from the root to X, there are no nodes with a value greater than X. You need to return the total number of good nodes in the tree.
Microsoft and Meta use the Depth-First Search interview pattern for this problem to evaluate your understanding of state propagation in tree traversals. It’s a "Medium" difficulty task that tests if you can pass information (the maximum value seen so far) down the recursion stack. It demonstrates a fundamental recursive thinking pattern.
This problem is solved using Depth-First Search (DFS).
max_so_far value to the recursive calls for the children.child.val >= max_so_far, the child is "good". Increment count.max_so_far = max(max_so_far, child.val).Tree: [3, 1, 4, 3, null, 1, 5]
3: Good. max=3.1: 1 < 3. Not good. max=3.3: 3 >= 3. Good. max=3.4: 4 >= 3. Good. max=4.1: 1 < 4. Not good.5: 5 >= 4. Good.
Total Good Nodes: 4.max_so_far variable as you go deeper, leading to incorrect "good" classifications.max_so_far that doesn't reset correctly when the recursion backtracks. It must be passed as a parameter.Tree problems that depend on the path from the root are perfect candidates for DFS where you pass a "state" variable (like sum, max, or min) as a parameter.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Largest Value in Each Tree Row | Medium | Solve | |
| Sum of Nodes with Even-Valued Grandparent | Medium | Solve | |
| Find Bottom Left Tree Value | Medium | Solve | |
| Reverse Odd Levels of Binary Tree | Medium | Solve | |
| Maximum Level Sum of a Binary Tree | Medium | Solve |