题目
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
Note:
The number of nodes in the given tree will be in the range [1, 100].
Each node’s value will be an integer in the range [0, 99].
Accepted
28,324
Submissions
42,338
分析
判断一棵二叉树上的value是否都相等,典型的采取递归的思想做;
先判断root.val及其左右孩子的val是否相等,若相等则直接分别判断左子树和右子树是否符合预期;若不相等则直接返回false即可。
特例,对于空树(None),则直接返回False;
code
# 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 isUnivalTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
if (root.left == None or root.left.val == root.val) and (root.right == None or root.right.val == root.val):
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
else:
return False