從前序與中序遍歷序列構造二叉樹 瘋狂遞迴吧

2021-10-06 09:40:28 字數 912 閱讀 9609

二叉樹的遍歷是遞迴來實現,兩樣反向構建二叉樹,也是用遞迴實現。原題鏈結

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。

注意:你可以假設樹中沒有重複的元素。

例如,給出

前序遍歷 preorder =[3

,9,20

,15,7

]中序遍歷 inorder =[9

,3,15

,20,7

]返回如下的二叉樹:

3/ \ 9

20/ \

157

二叉樹的基礎和三種遍歷方式,請看這篇文章:前序遍歷、中序遍歷和後序遍歷

直接上**,用**解釋更明了。

map map = new hashmap()

;// 全域性變數

public treenode buildtree

(int

preorder,

int[

] inorder)

return

buildtree

(preorder,

0, n-

1, inorder,

0, n-1)

;}/** * preleft 前序遍歷的開始位置

* preright 前序遍歷的結束位置

* inleft 中序遍歷的開始位置

* inright 中序遍歷的結束位置

**/private treenode buildtree

(int

preorder,

int preleft,

int preright,

int[

] inorder,

int inleft,

int inright)

從前序與中序遍歷序列構造二叉樹

題目描述 if inbegin inend 區間只有乙個結點,就是根結點 區間正常 int rootindex inbegin while rootindex inend 用前序的根劃分中序為兩個子區間 else 遞迴建立左子樹 root left buildtree preorder,pindex...

從前序與中序遍歷序列構造二叉樹

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。注意 你可以假設樹中沒有重複的元素。例如,給出前序遍歷 preorder 3,9,20,15,7 中序遍歷 inorder 9,3,15,20,7 返回如下的二叉樹 3 9 20 15 7python definition for a binary tree...

從前序與中序遍歷序列構造二叉樹

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。definition for a binary tree node.public class treenode class solution int rootidx left while rootidx right rootidx 前序 3 9 20 15 ...