Imagine you're exploring a binary tree where each node represents a checkpoint on your journey from the root to various destinations. A node is considered "good" if, throughout your entire path from the root to that node, you never encountered a value greater than the current node's value.
Your mission: Count how many "good" nodes exist in the entire binary tree.
What makes a node "good"?
- Start from the root and trace the path to the target node
- If no node along this path has a value greater than the target node's value, then it's good!
- Note: A node can equal values on the path and still be considered good
Input: The root of a binary tree
Output: An integer representing the count of good nodes
Example: In a tree with root value 3, if we reach a node with value 4 and the path was [3 โ 4], then node 4 is good because 3 โค 4.
Input & Output
Visualization
Time & Space Complexity
Single pass through all n nodes in the tree
Recursion stack depth equals tree height h, O(log n) for balanced tree, O(n) for skewed tree
Constraints
- The number of nodes in the binary tree is in the range [1, 105]
- Each node's value is between -104 and 104
- Tree nodes can have duplicate values
- A node is good if its value is greater than or equal to all ancestor values