Skip to main content

Univalued Binary Tree

LeetCode 1005 | Difficulty: Easy​

Easy

Problem 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.

When to use

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.

When to use

Level-order traversal, level-based aggregation, right/left side view.


Solutions​

Solution 1: C# (Best: 100 ms)​

MetricValue
Runtime100 ms
Memory25 MB
Date2021-10-02
Solution
/**
* 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​

ApproachTimeSpace
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • 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.