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
Count Univalue Subtrees INPUT Binary Tree Structure 5 1 5 5 5 5 root = [5,1,5,5,5,null,5] 7 nodes in tree Find all uni-value subtrees (same value in entire subtree) ALGORITHM STEPS DFS Post-Order Traversal 1 Start DFS Post-Order Process left, right, then node 2 Check Leaf Nodes Leaf = uni-value (count++) 3 Check Parent Nodes If children uni-value AND same value as parent 4 Return Result Count all uni-value subtrees Uni-value subtrees marked: 5 1 5 5 5 5 FINAL RESULT 4 Uni-value Subtrees Found Subtree 1: 5 leaf Subtree 2: 5 leaf Subtree 3: 5 leaf Subtree 4: 5 5 right subtree Output: 4 OK - 4 uni-value subtrees Key Insight: A subtree is uni-value if: (1) It's a leaf node, OR (2) Both children are uni-value subtrees AND all child values match the current node's value. Post-order DFS processes children first, enabling bottom-up validation. Node 1 fails because children (5,5) don't match parent value. TutorialsPoint - Count Univalue Subtrees | DFS Post-Order Traversal Approach
Asked in
Google 15 Facebook 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen