Given a binary tree, determine if it is a univalued binary tree, which means all nodes of the tree have the same value.
Input: [1,1,1,1,1,null,1]
Output: True
Input: [2,2,2,5,2]
Output: False
True
, as an empty tree can be considered trivially univalued.True
. Otherwise, return False
.We’ll use DFS for simplicity in the implementation.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isUnivalTree(root: TreeNode) -> bool:
if not root:
return True
def dfs(node: TreeNode, value: int) -> bool:
if not node:
return True
if node.val != value:
return False
return dfs(node.left, value) and dfs(node.right, value)
return dfs(root, root.val)
# Example usage:
# Constructing a binary tree [1,1,1,1,1,null,1]
root = TreeNode(1)
root.left = TreeNode(1)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
root.left.right = TreeNode(1)
root.right.right = TreeNode(1)
print(isUnivalTree(root)) # Should return True
root2 = TreeNode(2)
root2.left = TreeNode(2)
root2.right = TreeNode(2)
root2.left.left = TreeNode(5)
root2.left.right = TreeNode(2)
print(isUnivalTree(root2)) # Should return False
None
, return True
.False
.By using this approach, we ensure that all nodes are checked efficiently for the univalued property.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?