美文网首页
判断二叉树是否对称

判断二叉树是否对称

作者: loick | 来源:发表于2019-12-14 14:52 被阅读0次
    递归
        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
    

    相关文章

      网友评论

          本文标题:判断二叉树是否对称

          本文链接:https://www.haomeiwen.com/subject/pqwcnctx.html