1. 程式人生 > >【Leetcode_總結】965. 單值二叉樹 - python

【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/

思路:這個做的不太好,我用的先序遍歷 然後看看所有的值是不是相同的,判定是否是單值

程式碼:

# 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