Count Univalue Subtrees - Problem
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example:
- Input:
root = [5,1,5,5,5,null,5] - Output:
4 - Explanation: There are 4 uni-value subtrees
Input & Output
Example 1 — Mixed Tree with 4 Uni-value Subtrees
$
Input:
root = [5,1,5,5,5,null,5]
›
Output:
4
💡 Note:
The four uni-value subtrees are: three leaf nodes with value 5, and the right subtree rooted at 5 (which contains only node 5). The subtree rooted at node 1 is not uni-value because it contains both 1 and 5.
Example 2 — Single Node
$
Input:
root = [1]
›
Output:
1
💡 Note:
A single node is always a uni-value subtree by itself.
Example 3 — All Same Values
$
Input:
root = [5,5,5,5,5,5,5]
›
Output:
7
💡 Note:
All nodes have the same value, so every subtree is uni-value. Total 7 nodes = 7 uni-value subtrees.
Constraints
- The number of nodes in the tree is in the range [1, 1000]
- -1000 ≤ Node.val ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree [5,1,5,5,5,null,5] with mixed values
2
Identify Uniform
Find subtrees where all nodes have same value
3
Count Result
Total count of uni-value subtrees is 4
Key Takeaway
🎯 Key Insight: Use post-order traversal to check uniformity bottom-up efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code