965. Univalued Binary Tree
965. Univalued Binary Tree
如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回true,否则返回false。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root):
"""
:type: TreeNode
:rtype: bool
"""
# solution 1
def dfs(root, val):
if not root:
return True
if root.val != val:
return False
else:
return dfs(root.left, val) and dfs(root.right, val)
return dfs(root, root.val)
#solution 2
if not root:
return True
if root.right and root.right.val != root.val:
return False
if root.left and root.left.val != root.val:
return False
if root:
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)