#965
Univalued Binary Tree
EasyTreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchBreadth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can traverse the tree once and check if all nodes have the same value as the root. This is efficient and avoids unnecessary repeated checks.
⚙️
Algorithm
4 steps- 1Step 1: Get the value of the root node.
- 2Step 2: Use a Depth-First Search (DFS) or Breadth-First Search (BFS) to traverse the tree.
- 3Step 3: For each node, check if its value matches the root's value. If any node does not match, return false immediately.
- 4Step 4: If the traversal completes without mismatches, return true.
solution.py18 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def isUnivalTree(root):
9 if not root:
10 return True
11 value = root.val
12 def dfs(node):
13 if not node:
14 return True
15 if node.val != value:
16 return False
17 return dfs(node.left) and dfs(node.right)
18 return dfs(root)ℹ
Complexity note: The time complexity is linear because we visit each node exactly once. The space complexity is also O(n) in the worst case due to the recursion stack.
- 1A binary tree is uni-valued if all nodes have the same value as the root.
- 2Using DFS or BFS ensures we check each node efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.