力扣—965单值二叉树(多解法)

题目描述

如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。

只有给定的树是单值二叉树时,才返回 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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值