《劍指offer》重建二叉樹的解法

2021-08-20 22:33:58 字數 1308 閱讀 2539

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。

前序遍歷是先遍歷根結點,再依次遍歷左結點和右結點。

中序遍歷是先遍歷左結點,然後根結點,最後右結點。

那麼首先要去前序找到樹的根結點,然後以迴圈的方式從中序中找到這個根結點的位置,則根節點左右兩邊序列分別是二叉樹的左右子樹。找到左右子樹後,通過遞迴來找左右子樹內部的二叉樹節點。

class

treenode:

def__init__

(self, x):

self.val = x

self.left = none

self.right = none

class

solution:

# 返回構造的treenode根節點

defreconstructbinarytree

(self, pre, tin):

if(len(pre)==0

or len(tin)==0):

return

none

root=treenode(pre[0])

for i,item in enumerate(tin):

if(item==root.val):

root.left=self.reconstructbinarytree(pre[1:i+1],tin[:i])

root.right=self.reconstructbinarytree(pre[i+1:],tin[i+1:])

return root

if __name__=='__main__':

sl=solution()

pre=[4,2,1,3,6,5,7]

tin=[1,2,3,4,5,6,7]

treeroot1 = sl.reconstructbinarytree(pre, tin)

/**

* definition for binary tree

* public class treenode

* }*/public

class

solution

//遞迴的函式,建立後續左右結點與根結點的關係

public treenode rtbinarytree(int pre,int prestart,int preend,int in,int instart,int inend)

}return root;

}}

劍指offer 重建二叉樹

重建二叉樹2.cpp 定義控制台應用程式的入口點。題目描述 輸入乙個二叉樹的前序遍歷和中序遍歷,輸出這顆二叉樹 思路 前序遍歷的第乙個節點一定是這個二叉樹的根節點,這個節點將二叉樹分為左右子樹兩個部分,然後進行遞迴求解 include stdafx.h include vector using na...

《劍指offer》重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如,則重建二叉樹並返回。輸入乙個樹的前序和中序,例如輸入前序遍歷序列和中序遍歷序列 根據輸入的前序和中序,重建乙個該二叉樹,並返回該樹的根節點。definition for binary...

劍指offer 重建二叉樹

題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。definition for binary tree struct treenode class solution if ...