欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

力扣:101. 对称二叉树

程序员文章站 2022-05-16 14:56:22
...
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        from queue import Queue
        qu = Queue()
        qu.put(root)
        while not qu.empty():
                    # q 如果存本层节点的数值,就不完整,判断不了对称性
            q = [] # q存的是这层节点的所有子节点的数值,如果空就存None
            s = qu.qsize()
            for i in range(s):
                a = qu.get()
                if a.left:
                    qu.put(a.left)
                    q.append(a.left.val)
                else:
                    q.append(None)
                if a.right:
                    qu.put(a.right)
                    q.append(a.right.val)
                else:
                    q.append(None)
            for i in range(len(q)//2):
                if q[i] != q[len(q) - i - 1]:
                    return False
        return True