← DFS / Recursion

Pattern Recognition Drill

#141 — Count Good Nodes in Binary Tree

Medium Trees

The Problem

Count nodes where the node's value is greater than or equal to all values on the path from root.

What approach would you use?

Think about it before scrolling down.

Key Signals

DFS / Recursion

Pass max_so_far down. If node.val >= max_so_far, it's good. Update max and recurse. O(n).

Alt: Tree Recursion

Same DFS. Every node is visited once.

Common Trap

The initial max_so_far is root.val (root is always good). Don't forget to include the root.

← #140