Count Univalue Subtrees
Master this topic with zero to advance depth.
Count Univalue Subtrees
Count same val subtrees.
Level I: Brute Force (Check each node)
Intuition
A uni-value subtree is a subtree where all nodes have the same value. A brute force approach checks for every node n if all nodes in its subtree have the same value as n.val.
Thought Process
- Define
isUnival(node, val)helper. - In main
countfunction:- If
isUnival(root, root.val), increment count. - Recurse to children.
- If
Detailed Dry Run
| Node | Subtree Values | All Same? | Action |
|---|---|---|---|
| 1 | [1, 1, 1] | YES | count++ |
| 5 | [5, 5] | YES | count++ |
Level II: Recursive DFS (Parent Passing)
Intuition
Instead of checking every node as root, we can pass the parent's value down. If a node and its children all match that value, we have a candidate. This approach is slightly more efficient than checking every node but still redundant compared to bottom-up.
Logic
- For each node, check if it's the root of a unival subtree by matching it with its own value using an
isUnival(node, target)helper.
Detailed Dry Run
Node 5. isUnival(5, 5) -> returns true if all in 5's subtree are 5.
Level III: Optimal (Bottom-Up DFS)
Intuition
Thought Process
Instead of re-checking each subtree, we can use a bottom-up approach. A node is the root of a uni-value subtree if children are uni-value and match the parent's value.
Patterns
DFS Result Aggregation: Pass child status up to parents.
Complexity
- Time:
- Space:
Detailed Dry Run
| Node | Left Uni? | Right Uni? | Matches Children? | Count |
|---|---|---|---|---|
| Leaf | true | true | yes | count++ |
| Root | true | true | yes | count++ |
⚠️ Common Pitfalls & Tips
You must call DFS for both children before returning, even if one child is not a uni-value subtree. This is because the other child might still contain uni-value subtrees that need to be counted.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.