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 - DFS One Pass INPUT Binary Tree Structure 1 1 1 1 1 1 Array Representation: [1, 1, 1, 1, 1, null, 1] All nodes have value = 1 6 total nodes ALGORITHM STEPS 1 Get Root Value Store root.val as target val=1 2 DFS Traversal Visit each node recursively Check left and right subtrees 3 Compare Values node.val == target? Node 1: 1 == 1 [OK] Node 2: 1 == 1 [OK] ... all nodes [OK] 4 Return Result If all match: true If any mismatch: false FINAL RESULT All Nodes Verified 1 OK 1 OK 1 OK 1 1 1 Output: true Tree is Uni-valued! All 6 nodes have the same value: 1 Key Insight: DFS traverses the entire tree in O(n) time, comparing each node's value against the root value. Early termination: Return false immediately when a mismatch is found, avoiding unnecessary traversal. Space complexity: O(h) where h is height of tree (recursion stack). For balanced tree O(log n). TutorialsPoint - Univalued Binary Tree | DFS One Pass Comparison
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