Count Good Nodes In Binary Tree: the idea to remember.
Count tree nodes whose value is at least every value on their path from the root.
The core insight
Carry the maximum ancestor value down each root to node path.
Why it works
A node is good exactly when its value reaches or exceeds that path maximum; siblings require independent path state.
The mistake to avoid
Equal values qualify. Negative root values must also be counted.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Carry the maximum ancestor value down each root to node path.
public int goodNodes(TreeNode root) {
return helper(root, Integer.MIN_VALUE);
}
public int helper(TreeNode root, int max) {
if (root == null) return 0;
int res = root.val >= max ? 1 : 0;
res += helper(root.left, Math.max(root.val, max));
res += helper(root.right, Math.max(root.val, max));
return res;
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.