Univalued Binary Tree

Easy

Topics
TreeDFSBFS

A binary tree is univalued if every node has the same value. Given the root, return true if the tree is univalued, otherwise false.

Example 1

111111
Every node holds the same value, so the answer is true. Each node only needs comparing with its own parent — if that holds everywhere, it holds against the root by transitivity.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,1,1,1,1,null,1]
Output: true

Example 2

52222
The shaded node differs from the root, so the answer is false. One mismatch anywhere is enough, so the traversal can stop there.
Input:  root = [2,2,2,5,2]
Output: false

Constraints

  • 1 <= number of nodes <= 100
  • 0 <= Node.val <= 99
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every node must hold the same value, and the root's value is as good a reference as any. So walk the tree and compare each node against it, short-circuiting on the first mismatch.

Comparing against the root rather than against each node's parent is the simpler framing — equality is transitive, so "all equal to the root" and "every node equals its parent" are the same condition, but the first needs no state threaded through the recursion.

Approach

  1. DFS. A null node is vacuously fine.
  2. If the node's value differs from the root's, return false.
  3. Otherwise require both subtrees to pass.

The and short-circuits, so the right subtree is not explored once the left has failed.

Dry Run

tree      1              tree      2
         / \                      / \
        1   1                     2   2
       / \                       /
      1   1                     5

every node == 1  -> true        node 5 != 2  -> false,
                                and the recursion stops there

Complexity

  • Time — O(n) worst case, and less when a mismatch appears early.
  • Space — O(h): the recursion stack, up to O(n) on a degenerate tree. An iterative stack or queue would be O(w) in the width instead, which is better on a deep thin tree and worse on a bushy one.

Common Pitfalls

  • Returning false at a null node. Null is not a violation; the base case must be true.
  • Comparing each node only against its immediate children and forgetting that a single-child node still needs checking.
  • Using & rather than and in languages where that forces both sides to evaluate, losing the short-circuit.
  • Capturing the reference value from somewhere other than the root in a way that differs per call — the comparison target must be fixed.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def isUnivalTree(self, root):
        def dfs(node):
            if not node: return True
            if node.val != root.val: return False
            return dfs(node.left) and dfs(node.right)
        return dfs(root)
SensAI
Beta
Tap the mic to stop voice mode