183.Univalued Binary Tree

题目

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值