Univalued Binary Tree - Problem

A binary tree is uni-valued if every node in the tree has the same value.

Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

Input & Output

Example 1 — All Same Values
$ Input: root = [1,1,1,1,1,null,1]
Output: true
💡 Note: All nodes have value 1, so the tree is uni-valued
Example 2 — Different Values
$ Input: root = [2,2,2,5,2]
Output: false
💡 Note: One node has value 5 while others have value 2, so not uni-valued
Example 3 — Single Node
$ Input: root = [1]
Output: true
💡 Note: A single node tree is always uni-valued

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • 0 ≤ Node.val ≤ 99

Visualization

Tap to expand
Univalued Binary Tree ProblemExample 1: All Same111Result: trueExample 2: Different Values225Result: falseAlgorithm Steps1. Get root value2. Traverse tree (DFS/BFS)3. Compare each node4. Return false on mismatch5. Return true if all matchTime: O(n) | Space: O(h) where h is tree height
Understanding the Visualization
1
Input Tree
Binary tree with node values to check
2
Compare Values
Check if all nodes have same value as root
3
Return Result
True if all same, false if any differ
Key Takeaway
🎯 Key Insight: Compare all nodes against root value - stop early on first mismatch
Asked in
Google 15 Facebook 12 Amazon 8
28.5K 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