Given a binary tree
Output: 4
Explanation: Good nodes are 3 (root), 4, 3 (left child of 1), and 5. Node 1 is not good because 3 > 1 on its path.
Output: 3
Explanation: Good nodes are 3 (root), 3 (left child), and 4. Node 2 is not good because max on path is 3 > 2.
Constraints:
1 <= Number of nodes <= 105 -104 <= Node.val <= 104
Contents
Solution — DFS with Max Ancestor Complexity Analysis
Perform a pre-order DFS, passing the maximum value seen so far on the path from root to the
current node (
Algorithm:
- Start DFS at root with
maxSoFar = Integer.MIN_VALUE . - At each node: if
node.val >= maxSoFar , increment good count. - Update
maxSoFar = Math.max(maxSoFar, node.val) . - Recurse on left and right children with updated
maxSoFar .
Trace through Example 1: root = [3,1,4,3,null,1,5]
| Node | maxSoFar | val >= max? | Good? |
|---|---|---|---|
| 3 (root) | -∞ | 3 >= -∞ | Yes |
| 1 | 3 | 1 >= 3? No | No |
| 3 (left of 1) | 3 | 3 >= 3 | Yes |
| 4 | 3 | 4 >= 3 | Yes |
| 1 (left of 4) | 4 | 1 >= 4? No | No |
| 5 | 4 | 5 >= 4 | Yes |
Total good nodes = 4.
- Time: O(n) — every node is visited exactly once.
- Space: O(h) — recursion stack depth equals the tree height h.