Example 1
- Input
- root = [3,1,4,3,null,1,5]
- Output
- 4
3, the leaf 3, 4, and 5 each match or beat every ancestor above them, while 1 and the second 1 do not.
Given the root of a binary tree, count the nodes whose value is greater than or equal to every value on the path from the root. The root itself always counts as good.
A node X in a binary tree is good when no node on the path from the root down to X holds a value greater than X.
Given the root of a binary tree, return the total number of good nodes. The root has no ancestors above it, so it is always good.
1 <= number of nodes <= 10^5-10^4 <= Node.val <= 10^43, the leaf 3, 4, and 5 each match or beat every ancestor above them, while 1 and the second 1 do not.
Both 3 nodes and 4 are good, but 2 sits below a larger 3.
The root is good by definition.
The root -3 is good. The left child -4 is below -3 and fails; the right child -2 exceeds -3 and passes. Starting a maximum at zero would incorrectly reject every node.
The root 3 and both children are good: each child only compares with ancestor 3. Visiting 9 first must not raise the threshold for its sibling 4.
A good node ties or sets a record along its own root-to-node path. Only its ancestors matter: a larger value in a sibling subtree cannot disqualify it. In Example 1, the leaf 3 below 1 is good because its ancestors are 1 and 3, while the leaf 1 below 4 is not. Checking every ancestor separately repeats shared paths; carrying the path maximum gives each node the whole comparison in one number. Equal values count, and the starting maximum must handle negative values.
Reveal Path Check Per Node: intuition, complexity, and code
When a root-path predicate depends only on an aggregate such as maximum, minimum or sum, carry that aggregate with each pending node. Update it locally for children so siblings inherit the same prefix state without sharing later changes.