Count Univalue Subtrees
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
Count Univalue Subtrees
Count same val subtrees.
Approach 1
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
⏱ O(N^2)💾 O(H)
Detailed Dry Run
| Node | Subtree Values | All Same? | Action |
|---|---|---|---|
| 1 | [1, 1, 1] | YES | count++ |
| 5 | [5, 5] | YES | count++ |
Approach 2
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.
⏱ O(N^2)💾 O(H)
Detailed Dry Run
Node 5. isUnival(5, 5) -> returns true if all in 5's subtree are 5.
Approach 3
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:
⏱ O(N)💾 O(H)
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.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.