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.
DFS:
class Solution(object):
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.DFS(root.val,root)
def DFS(self,target,root):
if not root:
return True
left=self.DFS(target,root.left)
right=self.DFS(target,root.right)
return target==root.val and left and right
class Solution(object):
def isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if root.right:
if root.right.val!=root.val:
return False
if root.left:
if root.left.val!=root.val:
return False
return self.isUnivalTree(root.right) and self.isUnivalTree(root.left)