Count Good Nodes in Binary Tree
Difficulty: Medium · Pattern: Trees & BST · LeetCode #1448
A node X is good if no node on the path from the root to X has a value greater than X. Return the number of good nodes in the tree. The root is always good.
Examples
text
3*
/ \
1 4*
/ / \
3* 1 5*
[3,1,4,3,null,1,5] → 4 (* = good)
[3,3,null,4,2] → 3
[1] → 1Hints
- What do you need to know about the path above a node to decide whether it's good?
- Only one number: the maximum value on that path.
Approach
Pre-order DFS with an accumulator maxSoFar:
- The node is good if
node.val >= maxSoFar. Note>=: equal values still count. - Recurse into the children with
max(maxSoFar, node.val).
This is the top-down state pattern: information flows down the tree as a parameter. Compare it with Balanced Tree or Diameter, where information flows up through return values.
Complexity
Time: O(n). Space: O(h).
Python solution
def goodNodes(root):
def dfs(node, mx):
if not node:
return 0
good = 1 if node.val >= mx else 0
mx = max(mx, node.val)
return good + dfs(node.left, mx) + dfs(node.right, mx)
return dfs(root, float('-inf'))JavaScript solution
function goodNodes(root) {
const dfs = (node, mx) => {
if (!node) return 0;
const good = node.val >= mx ? 1 : 0;
mx = Math.max(mx, node.val);
return good + dfs(node.left, mx) + dfs(node.right, mx);
};
return dfs(root, -Infinity);
}