mediumTreesMicrosoftGoogleAmazon
Good Nodes Accumulator
A hydrologist counts unblocked watershed channels. A point is an unblocked 'good reservoir' if its elevation matches or exceeds all upstream elements.
Given a binary tree, a node `x` in the tree is named **good** if in the path from root to `x` there are no nodes with a value greater than `x`. Return the number of good nodes in the binary tree.
Choose approach
3
✓cur
1
4
3
1
5
1/10
Narrationstep 1 of 10
Evaluate reservoir Node 3. Max altitude upstream is 3. Node value is >= max: fully unblocked!
Variables
currNode=3
upstreamMax=3
isGood=true
goodReservoirsCount=1
How to think about it
- Start at the root, passing its value as structural max.
- Evaluate children: if children val exceeds current max, increment running count.
- Bubble counts bottom-up or aggregate recursively.
Edge cases to catch in interview
- Perfect linear descendancy (strictly increasing values) -> all nodes are good.
- Strictly decreasing branch lines -> only the root is good.
Examples
Example 1
4{"arr":[3,1,4,3,null,1,5]}
Example 2
3{"arr":[3,3,null,4,2]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed