判断二叉树是否对称

递归
    def isSymmetric(self, root: TreeNode) -> bool:
        def st(A, B):
            if A == B == None:
                return True
            if not A or not B:
                return False
            return A.val==B.val and st(A.left, B.right) and st(A.right, B.left)
        
        if not root:
            return True
        return st(root.left, root.right)
非递归
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        stack = [(root.left, root.right)]
        while stack:
            l, r = stack.pop()
            if l == r == None:
                continue
            if not l or not r or l.val != r.val:
                return False
            stack.append((l.left, r.right))
            stack.append((l.right, r.left))
        return True
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容