Univalued Binary Tree

Easy · Trees · Tree · Depth-First Search · Breadth-First Search · Binary Tree

Problem

A binary tree is uni-valued if every node in it holds the same value.

Given the root of a binary tree, return true if the tree is uni-valued and false otherwise.

Examples

Input: root = [4,4,4,null,4]
Output: true

All four nodes hold 4.

Input: root = [4,4,4,4,7]
Output: false

One leaf holds 7, so the values are not all the same.

Input: root = [2,2,2,5,2]
Output: false

The 5 sits two levels down; every node has to be checked, not just the root's children.

Constraints

Approaches

Follow-up

With an early exit the walk stops at the first mismatch, so a tree whose root's children already differ is answered in constant time. The use cases count every uni-valued subtree, which needs answers from both children (a post-order walk), and relax the rule to one value per level.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…