[LeetCode]#965. Univalued Binary Tree
Jan 22, 2021
Environment: Python 3.8
Key technique: TreeNode
A binary tree is univalued if every node in the tree has the same value.
Return true
if and only if the given tree is univalued.
Example 1:
Input: [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: [2,2,2,5,2]
Output: false
Analysis:
- val=2, val.left=2, val.right=2. (True)
- val=2, val.left=5, val.right=2 (False)
- val=2, val.left=2, val.right=null (True)
- Return False
Solution:
class Solution:
def isUnivalTree(self, root):
if not root:
return True
if root.left:
if root.val != root.left.val:
return False
if root.right:
if root.val != root.right.val:
return Falseleft_b = self.isUnivalTree(root.left)
right_b = self.isUnivalTree(root.right)
ans=left_b and right_b
return ans
Submissions:
Reference: