Problem Description
Given a binary tree, a node X is considered good if on the path from the root to X there are no nodes with a value greater than X. The task is to count the number of good nodes in the binary tree.
Key Insights
- Perform a tree traversal (DFS or BFS) from the root.
- Keep track of the maximum value encountered along the current path.
- A node is "good" if its value is greater than or equal to the maximum value seen so far.
- Update the maximum value as you traverse deeper in the tree.
- The root is always a good node.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes, since each node is visited exactly once. Space Complexity: O(h), where h is the height of the tree (O(n) in the worst-case of a skewed tree).
Solution
We can solve this problem using Depth-First Search (DFS) recursion. Starting from the root, we pass along the current maximum value encountered on the path. For each node, we check if its value is greater than or equal to this maximum. If it is, we count it as a good node and update the maximum value if necessary. This process is continued recursively for both the left and right children of the node. Finally, we sum the counts from both subtrees.