這篇文章主要介紹“Python用非遞歸實現(xiàn)二叉樹中序遍歷代碼分享”,在日常操作中,相信很多人在Python用非遞歸實現(xiàn)二叉樹中序遍歷代碼分享問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python用非遞歸實現(xiàn)二叉樹中序遍歷代碼分享”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
創(chuàng)新互聯(lián)公司秉承實現(xiàn)全網(wǎng)價值營銷的理念,以專業(yè)定制企業(yè)官網(wǎng),成都網(wǎng)站建設、成都網(wǎng)站制作,成都微信小程序,網(wǎng)頁設計制作,手機網(wǎng)站制作設計,成都全網(wǎng)營銷幫助傳統(tǒng)企業(yè)實現(xiàn)“互聯(lián)網(wǎng)+”轉型升級專業(yè)定制企業(yè)官網(wǎng),公司注重人才、技術和管理,匯聚了一批優(yōu)秀的互聯(lián)網(wǎng)技術人才,對客戶都以感恩的心態(tài)奉獻自己的專業(yè)和所長。
中序遍歷其實和就是先找到最左邊節(jié)點,然后是其上級節(jié)點,再到上級節(jié)點的右邊節(jié)點。
比如下面的中序遍歷結果就是 DBEAFC

非遞歸實現(xiàn)邏輯,我想的這個比較笨。就是用一個隊列做棧,先按照左邊遍歷壓入棧中;當?shù)阶筮吶~子節(jié)點時候,讀取并刪除關聯(lián);推出棧回到上一級節(jié)點,如果上級節(jié)點沒有右節(jié)點,則讀取繼續(xù)刪除;如果有,則遍歷右節(jié)點;為了防止右邊遍歷返回時候再次讀取父節(jié)點;要記錄下上次被推出節(jié)點,如果是右節(jié)點,則不讀取父節(jié)點信息。
代碼寫的很難看,不去雕琢了,見笑。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: traversalList = [] nodeList = [] # similar as Preorder traversal, the only change is that the value of node is recored when the node doesn't have left sub-node; new object removedNode as popped node, if a node's right sub-node is removedNode, then it should be popped both. if root != None: nodeList.append(root) currentNode = root removedNode = None while nodeList != []: if currentNode.left != None: currentNode = currentNode.left nodeList.append(currentNode) elif currentNode.right == None or currentNode.right == removedNode: if currentNode.right == None: traversalList.append(currentNode.val) removedNode = nodeList.pop() if nodeList!= []: currentNode = nodeList[-1] currentNode.left = None elif currentNode.right !=None: traversalList.append(currentNode.val) currentNode = currentNode.right nodeList.append(currentNode) return traversalList
到此,關于“Python用非遞歸實現(xiàn)二叉樹中序遍歷代碼分享”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
新聞標題:Python用非遞歸實現(xiàn)二叉樹中序遍歷代碼分享
分享網(wǎng)址:http://chinadenli.net/article20/ggjgjo.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供外貿網(wǎng)站建設、動態(tài)網(wǎng)站、企業(yè)建站、標簽優(yōu)化、全網(wǎng)營銷推廣、網(wǎng)頁設計公司
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)