101. 对称二叉树

https://leetcode-cn.com/problems/symmetric-tree/

解法一:递归

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def helper(t1, t2):    #辅助函数
            if not t1 and not t2:    #都为空
                return True
            elif not t1 or not t2:    #只有一个为空
                return False
            else:    #都不为空
                if t1.val == t2.val:
                    #分别反向访问t1,t2的左右子树
                    return helper(t1.left, t2.right) and helper(t1.right, t2.left)
                else:
                    return False
        return helper(root, root)    #都从根开始

解法二:层序

分别对该树进行从左到右和从右到左的层序遍历,每次分别比较取出的结点,不相等则false

最后更新于