LeetCode 965 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.

题目分析及思路

题目要求当输入的二叉树的每个结点都有相同的值则返回true,否则返回false。可以使用队列保存每个节点,用val保存root节点的值。如果弹出的数字不等于val不等于root节点就立刻返回false。如果全部判断完成之后仍然没有返回false,说明所有的数字都等于root,返回true。

python代码​

# 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

        """

        q=collections.deque()

        q.append(root)

        val = root.val

        while q:

            node = q.popleft()

            if not node:

                continue

            if val != node.val:

                return False

            q.append(node.left)

            q.append(node.right)

        return True

            

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10202907.html