判断二叉树是否对称

2019-12-14  本文已影响0人  loick
递归
    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
上一篇 下一篇

猜你喜欢

热点阅读