CodeArchon

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!

1def goodNodes(root: TreeNode) -> int:
2 def dfs(node: TreeNode, max_val: int) -> int:
3 if not node:
4 return 0
5 count = 1 if node.val >= max_val else 0
6 next_max = max(max_val, node.val)
7 count += dfs(node.left, next_max)
8 count += dfs(node.right, next_max)
9 return count
10 return dfs(root, root.val)
Variables
currNode=3
upstreamMax=3
isGood=true
goodReservoirsCount=1

How to think about it

  1. Start at the root, passing its value as structural max.
  2. Evaluate children: if children val exceeds current max, increment running count.
  3. 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 14
{"arr":[3,1,4,3,null,1,5]}
Example 23
{"arr":[3,3,null,4,2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed