LC 速查

HOT 100索引 › B8 二叉树 Binary Tree

LC 101对称二叉树Symmetric Tree 简单

判断二叉树是否关于根轴左右镜像对称。

思路 递归双参比较:对应位置值相等,且外侧对外侧、内侧对内侧均对称。时间 O(n)。

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def mirror(a, b):
            if not a and not b:
                return True
            if not a or not b or a.val != b.val:
                return False
            ok1 = mirror(a.left, b.right)
            ok2 = mirror(a.right, b.left)
            return ok1 and ok2
        return mirror(root, root)
← 上一题 翻转二叉树二叉树的直径 下一题 →