题目描述
如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true
;否则返回 false
。
示例 1:
输入:[1,1,1,1,1,null,1]
输出:true
示例 2:
输入:[2,2,2,5,2]
输出:false
解题思路
1. 遍历得到序列再判断
对数进行前序遍历,中序后序均可,得到遍历序列,再判断是否全为一个元素
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def pre_order(self, root):
if not root:
return []
return [root.val] + self.pre_order(root.left) + self.pre_order(root.right)
def isUnivalTree(self, root):
temp = self.pre_order(root)
return True if len(set(temp)) == 1 else False
S = Solution()
n1 = TreeNode(1)
n2 = TreeNode(1); n3 = TreeNode(1)
n4 = TreeNode(2); n5 = TreeNode(1); n6 = TreeNode(1)
n1.left = n2; n1.right = n3
n2.left = n4; n2.right = n5; n3.right = n6
print(S.isUnivalTree(n1))
2 递归
定义一个变量,保存根节点的值,变量在__init__函数中定义,然后进行递归
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.value = None
def isUnivalTree(self, root):
if not root:
return True
if not self.value:
self.value = root.val
if self.value != root.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
S = Solution()
n1 = TreeNode(1)
n2 = TreeNode(1); n3 = TreeNode(1)
n4 = TreeNode(2); n5 = TreeNode(1); n6 = TreeNode(1)
n1.left = n2; n1.right = n3
n2.left = n4; n2.right = n5; n3.right = n6
print(S.isUnivalTree(n1))