Introduction
Good Node means:
- current node value
- is greater than or equal to
- every previous node
in root-to-node path
Condition:
node.value >= maximum value seen in pathExample:
3
/ \
1 4
/ / \
3 1 5
Good Nodes:
3 4 5 3
Count:4
Explanation:
Every good node maintains maximum value in current path. This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5Approach : Recursive DFS Solution
Explanations:
Explanation:
The idea is:
- traverse tree using DFS
- maintain maximum value
in current path
Steps:
- Visit current node.
- Compare node with path maximum.
- Count node if valid.
- Update maximum value.
- Recurse left subtree.
- Recurse right subtree.
Condition:
current.value >= pathMaximum This approach:
- uses DFS recursion
- tracks maximum value dynamically
Dry Run
Visit:3
Path maximum:
3
Good node count:
1
Visit:
4
Updated maximum:
4
Good node count:
2
Visit:
5
Updated maximum:
5
Good node count:
3
Practice :