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.
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 100].
0 <= Node.val < 100
Solutions
Solution 1: DFS
We denote the value of the root node as $x$, and then design a function $\text{dfs}(\text{root})$, which indicates whether the current node's value is equal to $x$ and its left and right subtrees are also univalued binary trees.
In the function $\text{dfs}(\text{root})$, if the current node is null, return $\text{true}$; otherwise, if the current node's value is equal to $x$ and its left and right subtrees are also univalued binary trees, return $\text{true}$; otherwise, return $\text{false}$.
In the main function, we call $\text{dfs}(\text{root})$ and return the result.
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the number of nodes in the tree.
1 2 3 4 5 6 7 8 9101112131415
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defisUnivalTree(self,root:Optional[TreeNode])->bool:defdfs(root:Optional[TreeNode])->bool:ifrootisNone:returnTruereturnroot.val==xanddfs(root.left)anddfs(root.right)x=root.valreturndfs(root)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisUnivalTree(root*TreeNode)bool{x:=root.Valvardfsfunc(*TreeNode)booldfs=func(root*TreeNode)bool{ifroot==nil{returntrue}returnroot.Val==x&&dfs(root.Left)&&dfs(root.Right)}returndfs(root)}