Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - DFS
A binary tree is uni-valued if all of its nodes have the same value. To determine this, we need to traverse the binary tree and check whether the value of every node matches the value of the root node.
Approach
- Start from the root: Consider the value of the root node as the reference value.
- Traverse the tree: Use either a Depth First Search (DFS) or Breadth First Search (BFS) to visit all nodes in the tree.
- Comparison: Compare the value of each node with the reference value during traversal.
- Return result: If all nodes match the reference value, return
true
. Otherwise, returnfalse
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. We need to visit each of then
nodes in the tree once. - 🧺 Space complexity:
O(h)
. The space used by the traversal stack is proportional to the heighth
of the binary tree:- In the best case of a balanced binary tree,
h = log(n)
. - In the worst case of a skewed binary tree,
h = n
.
- In the best case of a balanced binary tree,