Univalued Binary Tree - Problem
Univalued Binary Tree

Imagine you have a binary tree where every node contains a value. A uni-valued binary tree is one where every single node has the exact same value - like a perfectly uniform tree where all nodes share the same identity!

Your task is simple yet elegant: given the root of a binary tree, determine whether this tree is uni-valued. Return true if all nodes have the same value, or false if there's even one node that differs.

This problem tests your ability to traverse a tree structure and check a global property across all nodes. It's a perfect introduction to tree traversal algorithms and a common building block for more complex tree problems.

Input & Output

example_1.py โ€” Simple Univalued Tree
$ Input: root = [1,1,1,1,1,null,1]
โ€บ Output: true
๐Ÿ’ก Note: All nodes in the tree have the value 1, making this a perfect univalued binary tree.
example_2.py โ€” Mixed Values Tree
$ Input: root = [2,2,2,5,2]
โ€บ Output: false
๐Ÿ’ก Note: The tree contains nodes with value 2 and one node with value 5. Since not all nodes have the same value, this is not univalued.
example_3.py โ€” Single Node Tree
$ Input: root = [5]
โ€บ Output: true
๐Ÿ’ก Note: A tree with only one node is always univalued since there's only one value to consider.

Constraints

  • The number of nodes in the tree is in the range [1, 100]
  • 0 โ‰ค Node.val โ‰ค 99
  • Follow-up: Can you solve this iteratively using BFS?

Visualization

Tap to expand
Uniform Team Check - Tree Style1Captain (Reference)1111Inspection Results:Captain: 1 โœ“Member 1: 1 โœ“Member 2: 1 โœ“Member 3: 1 โœ“Member 4: 1 โœ“โœ“ UNIFORM TEAM!
Understanding the Visualization
1
Set Reference
Use the root node's value as the standard uniform everyone should match
2
Inspect Each Member
Visit each node in the tree and compare its value to the reference
3
Early Detection
If any node differs from reference, immediately return false
4
Complete Verification
If all nodes match the reference, the tree is univalued
Key Takeaway
๐ŸŽฏ Key Insight: Instead of comparing every node with every other node (O(nยฒ)), we only need to compare each node with one reference value (the root), achieving optimal O(n) time complexity!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.5K Views
Medium Frequency
~8 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen