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
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.
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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code