给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

But the following [1,2,2,null,3,null,3] is not:

Solution in 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 isSymmetric(self, root: TreeNode) -> bool:
        def isTreeSymmetric(root1, root2):
            if root1 == None and root2 == None:
                return True
            elif (root1 == None and root2) or (root1 and root2 == None):
                return False
            elif root1.val == root2.val:
                return isTreeSymmetric(root1.left, root2.right) and isTreeSymmetric(root1.right, root2.left)
        if root == None:
            return True
        else:
            return isTreeSymmetric(root.left, root.right)
最后修改日期: 2021年1月6日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。