101. 對(duì)稱二叉樹

我的思路為中序遍歷和逆中序遍歷的結(jié)果是相同的。這種思路是錯(cuò)的,原因在于
[1,2,2,2,null,2]這種情況下回出現(xiàn)錯(cuò)誤。

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        
        queue1 = []
        queue2 = []
        self.Inorder(root,queue1)
        self.inverseInorder(root, queue2)
        if queue1 == queue2:
            return True
        else:
            return False
        
    def Inorder(self, root,queue):
        if root is None:
            return 
        self.Inorder(root.left,queue)
        queue.append(root.val)
        self.Inorder(root.right,queue)
        
    def inverseInorder(self, root,queue):
        if root is None:
            return 
        self.inverseInorder(root.right,queue)
        queue.append(root.val)
        self.inverseInorder(root.left,queue)

隨后看了官方解答,進(jìn)行了遞歸算法的實(shí)現(xiàn)。

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        return self.isMirror(root,root)
    def isMirror(self, rootleft, rootright):
        if rootleft == None and rootright == None:
            return True
        if rootleft == None or rootright == None:
            return False
        if rootleft.val != rootright.val:
            return False
        
        return self.isMirror(rootleft.left, rootright.right) and self.isMirror(rootleft.right, rootright.left)

因?yàn)橥ㄟ^遞歸的方式可以實(shí)現(xiàn),自然想到通過棧的方式(其實(shí)在這道題中用隊(duì)列也可以實(shí)現(xiàn))。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        stack = [root.left,root.right]
        
        while stack:
            t1 = stack.pop()
            t2 = stack.pop()
            if (not t1 and not t2):
                continue
            if(not t1 or not t2):
                return False
            if (t1.val != t2.val):
                return False
            stack.append(t1.left)
            stack.append(t2.right)
            stack.append(t1.right)
            stack.append(t2.left)
        return True
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容