【Leetcode_总结】965. 单值二叉树 - python

Q:

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

只有给定的树是单值二叉树时,才返回 true;否则返回 false

示例 1:

输入:[1,1,1,1,1,null,1]
输出:true

示例 2:

输入:[2,2,2,5,2]
输出:false

链接:https://leetcode-cn.com/problems/univalued-binary-tree/description/

思路:这个做的不太好,我用的先序遍历 然后看看所有的值是不是相同的,判定是否是单值

代码:

扫描二维码关注公众号,回复: 4867157 查看本文章
# 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 root: TreeNode
        :rtype: bool
        """
        res = []
        res_ = self.front_digui(res, root)
        print(res_)
        if len(list(set(res_))) == 1:
            return True
        else:
            return False

    def front_digui(self, res, root):
        if root == None:
            return 
        res.append(root.val)
        self.front_digui(res,root.left)
        self.front_digui(res,root.right)
        return res

看AC的代码,其中使用堆栈的思路很好,就是将叶子节点压栈,分别于根节点的值做比较,知道栈空

class Solution:
    def isUnivalTree(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:return True
        stack=[]
        stack.append(root)
        while stack:
            node=stack.pop()
            if node:
                if node.val!=root.val:return False
                stack.append(node.left)
                stack.append(node.right)
        return True

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86021792