Problem
Given a binary tree root
, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Examples
Example 1:
graph TD A(3) B(1) C(4) D(3) E(1) F(5) A:::blue --> B A:::blue --> C:::blue B --> D:::blue B ~~~ N1:::hidden C:::blue --> E C:::blue --> F:::blue classDef blue fill:#ADD8E6,stroke:#000,stroke-width:1px; classDef hidden display:none
|
|
Example 2:
graph TD A(3) B(3) C(null) D(4) E(2) A:::blue --> B:::blue A:::blue ~~~ C:::hidden B:::blue --> D:::blue B:::blue --> E:::blue classDef blue fill:#ADD8E6,stroke:#000,stroke-width:1px; classDef hidden display:none
|
|
Example 3:
|
|
Solution
Method 1 - Preorder Traversal with Max Tracking
- This problem can be solved using a recursive depth-first search (DFS).
- As we traverse down the binary tree, we keep track of the maximum value encountered so far (
max_val
) along the path from the root to the current node. - A node is considered good if its value is greater than or equal to
max_val
. - For each node:
- Compare its value with
max_val
. - If the node value is greater than or equal to
max_val
, count it as good. - Update
max_val
to the maximum of the currentmax_val
and the node’s value.
- Compare its value with
- Recur for the left and right children of the node.
- Aggregate the counts of good nodes.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes in the tree. As each node of the binary tree is visited exactly once. - 🧺 Space complexity:
O(h)
is determined by the depth of recursion, whereh
is the height of the tree. In the worst case (skewed tree), this could beO(n)
.