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 tree is uni-valued, or False otherwise.
Function Signature
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
def is_unival_tree(root: Optional[TreeNode]) -> bool:
...
Rules
-
In the examples the tree is written as a level-order list, where
None
marks a missing child. The function receives the root
TreeNode
built from that list.
-
A tree with a single node is uni-valued.
Constraints
-
The number of nodes in the tree is in the range 1 to 100.
-
0 <= node.val < 100
Examples
Input: root = [1, 1, 1, 1, 1, None, 1]
Output: True
The root has two children with value 1. The left child has two children with value 1, and the right child has only a right child, also 1. All six nodes have value 1.
Input: root = [2, 2, 2, 5, 2]
Output: False
The left child of the root has a left child with value 5, while every other node has value 2, so the values are not all the same.
Input: root = [0]
Output: True
A single node trivially has the same value as every node in the tree.