Univalued Binary Tree
EasyUpdated: Aug 2, 2025
Practice on:
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.
Examples
Example 1:
1
/ \
1 1
/ \ \
1 1 1
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
2
/ \
2 2
/ \
5 2
Input: root = [2,2,2,5,2]
Output: false
Solution
Method 1 - DFS
A binary tree is uni-valued if all of its nodes have the same value. To determine this, we need to traverse the binary tree and check whether the value of every node matches the value of the root node.
Approach
- Start from the root: Consider the value of the root node as the reference value.
- Traverse the tree: Use either a Depth First Search (DFS) or Breadth First Search (BFS) to visit all nodes in the tree.
- Comparison: Compare the value of each node with the reference value during traversal.
- Return result: If all nodes match the reference value, return
true. Otherwise, returnfalse.
Code
Java
class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def dfs(node: Optional[TreeNode], val: int) -> bool:
if not node:
return True
if node.val != val:
return False
return dfs(node.left, val) and dfs(node.right, val)
ref_val = root.val
return dfs(root, ref_val)
Python
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null) {
return true;
}
int refVal = root.val;
return dfs(root, refVal);
}
private boolean dfs(TreeNode node, int val) {
if (node == null) {
return true;
}
if (node.val != val) {
return false;
}
return dfs(node.left, val) && dfs(node.right, val);
}
}
Complexity
- ⏰ Time complexity:
O(n). We need to visit each of thennodes in the tree once. - 🧺 Space complexity:
O(h). The space used by the traversal stack is proportional to the heighthof the binary tree:- In the best case of a balanced binary tree,
h = log(n). - In the worst case of a skewed binary tree,
h = n.
- In the best case of a balanced binary tree,