101. 對稱二叉樹

問題描述

給定一個二叉樹,檢查它是不是鏡像對稱的。python

例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。code

1
   / \
  2   2
 / \ / \
3  4 4  3

可是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:遞歸

1
   / \
  2   2
   \   \
   3    3

解決方案

遞歸:io

class Solution:
    def isSymeetric(self, root):
        if root is None:
            return True
        else:
            return self.isMirror(root.left, root.right)

    def isMirror(self, left, right):
        if left is None and right is None:
            return True
        if left is None or right is None:
            return False
        if left.val == right.val:
            outPair = self.isMirror(left.left, right.right)
            inPair = self.isMirror(left.right, right.left)
            return outPair and inPair
        else:
            return False

迭代:class

class Solution:
    def isSymmetric(self, root):
        if root is None:
            return True

        stack = [[root.left, root.right]]

        while len(stack) > 0:
            pair = stack.pop(0)
            left = pair[0]
            right = pair[1]

            if left is None and right is None:
                continue
            if left is None or right is None:
                return False
            if left.val == right.val:
                stack.insert(0, [left.left, right.right])

                stack.insert(0, [left.right, right.left])
            else:
                return False
        return True
相關文章
相關標籤/搜索