Univalued Binary Tree
LeetCode 1005 | Difficulty: Easyβ
EasyProblem Descriptionβ
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.
Example 1:

Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:

Input: root = [2,2,2,5,2]
Output: false
Constraints:
- The number of nodes in the tree is in the range `[1, 100]`.
- `0 <= Node.val < 100`
Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree
Approachβ
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
Tree BFS (Level-Order)β
Use a queue to process the tree level by level. At each level, process all nodes in the queue, then add their children. Track the level size to know when one level ends and the next begins.
Level-order traversal, level-based aggregation, right/left side view.
Solutionsβ
Solution 1: C# (Best: 100 ms)β
| Metric | Value |
|---|---|
| Runtime | 100 ms |
| Memory | 25 MB |
| Date | 2021-10-02 |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool IsUnivalTree(TreeNode root) {
if(root==null) return false;
Stack<TreeNode> s = new Stack<TreeNode>();
int unival = root.val;
s.Push(root);
while(s.Count != 0)
{
var popped = s.Pop();
if (popped.val != unival)
{
return false;
}
if(popped.left != null)
{
s.Push(popped.left);
}
if(popped.right != null)
{
s.Push(popped.right);
}
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.