LeetCode——Question 101 (python): Symmetric binary tree

topic

Given a binary tree, check whether it is mirror symmetric.
For example, the binary tree [1,2,2,3,4,4,3] is symmetric.
Insert image description here
But the following [1,2,2,null,3,null,3] is not mirror symmetric:
Insert image description here

Code that runs successfully
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution(object):
    def isSymmetric(self, root):
        if not root:
            return True
        que = deque([root.left, root.right])
        while que:
            node1 = que.pop()
            node2 = que.pop()
            if not node1 or not node2:
                if not node1 and not node2:
                    continue
                return False
            if node1.val != node2.val:
                return False
            # 添加left.left, right.right, left.right,left.right
            que.append(node1.left)
            que.append(node2.right)
            que.append(node1.right)
            que.append(node2.left)
        return True
operation result

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45398231/article/details/105778026