Python:對稱的二叉樹


牛客網上的劍指 offer的在線編程:

題目描述

請實現一個函數,用來判斷一顆二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的鏡像是同樣的,定義其爲對稱的。
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        def is_same(p1, p2):
            if not p1 and not p2:
                return True
            if (p1 and p2) and p1.val == p2.val:
                    return is_same(p1.left, p2.right) and is_same(p1.right, p2.left)
            return False
        if not pRoot:
            return True
        if not pRoot.left and pRoot.right:
            return False
        if pRoot.left and not pRoot.right:
            return False
        return is_same(pRoot.left, pRoot.right)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章