Passing Values Down (State)
Learn how to pass information (state) from parents to children in DFS.
Examples
Good nodes are in bold: [3,1,4,3,null,1,5].
Path 3->1->3: Node 3 is good because 3 >= 3.
Path 3->4->5: Node 5 is good because 5 >= 4.
Problem Understanding
We need to count the Good Nodes in a binary tree.
A node is Good if, in the path from the Root to that Node, there are no nodes with a value greater than the node itself.
In simpler terms: Is this node result the largest (or equal largest) value we've seen so far on this path?
Algorithm Strategy (Top-Down State)
We use Pre-order DFS (Top-Down) to solve this.
We need to pass the Maximum Value Seen So Far down to children. This 'state' allows each child to decide if it is 'good' without looking back up the tree.
- State:
maxVal(the maximum value encountered on the current path). - Check: If
node.val >= maxVal, the node is Good. Increment count. - Update: New state for children is
max(maxVal, node.val). - Recurse: Call DFS on left and right children with the updated state.
Interactive Visualization
Node 3. Max So Far: 3. 3 >= 3 ? YES (+1).
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.- Problem Understanding
- Algorithm Strategy (Top-Down State)
- Interactive Visualization
- Dry Run: [3, 1, 4, 3, null, 1, 5]
- Edge Cases
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
