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

2021-09-27 04:47:20 字數 2271 閱讀 6517

/**

* definition for a binary tree node.

* public class treenode

* }*/class

solution

int rootvalue = preorder[0]

;//根結點就是前序遍歷preorder的第乙個元素

int leftcount;

for(leftcount =

0; leftcount < inorder.length; leftcount++)}

treenode root =

newtreenode

(rootvalue)

;//將根結點的值裝入結點

//將preorder中的元素從preorder[1]到preorder[1 + leftcount](左閉右開,不包括後者)拷貝到新的陣列leftpreorder中

int[

] leftpreorder = arrays.

copyofrange

(preorder,1,

1+ leftcount)

;//將inorder中的元素從inorder[0]到inorder[leftcount]拷貝到leftinorder中

int[

] leftinorder = arrays.

copyofrange

(inorder,

0, leftcount)

;//遞迴

root.left =

buildtree

(leftpreorder,leftinorder)

;//同理,寫出右子樹的過程

int[

] rightpreorder = arrays.

copyofrange

(preorder, leftcount +

1, preorder.length)

;int

rightinorder = arrays.

copyofrange

(inorder, leftcount +

1, inorder.length)

; root.right =

buildtree

(rightpreorder,rightinorder)

;return root;

}}

同理可寫出從中序與後序遍歷序列構造二叉樹的**:

/**

* definition for a binary tree node.

* public class treenode

* }*/class

solution

int rootvalue = postorder[postorder.length -1]

;int leftcount;

for(leftcount =

0; leftcount < inorder.length; leftcount++)}

treenode root =

newtreenode

(rootvalue)

;//這裡注意arrays.copyofrange()方法拷貝時的範圍是:左閉右開

int[

] leftinorder = arrays.

copyofrange

(inorder,

0, leftcount)

;int

leftpostorder = arrays.

copyofrange

(postorder,

0, leftcount)

; root.left =

buildtree

(leftinorder, leftpostorder)

;int

rightinorder = arrays.

copyofrange

(inorder, leftcount +

1, postorder.length)

;int

rightpostorder = arrays.

copyofrange

(postorder, leftcount, postorder.length -1)

; root.right =

buildtree

(rightinorder, rightpostorder)

;return root;

}}

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

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

由前序序列與中序序列實現後序遍歷

二叉樹是一種特殊的樹,二叉樹只有兩個分支,分別是該節點的左兒子和右兒子。前序遍歷 就是先遍歷根節點,然後再訪問左子樹與右子樹。遍歷子樹的時候同樣也是先遍歷根節點然後在遍歷他的左子樹與右子樹。中序遍歷 先遍歷左子樹,在遍歷根節點,最後遍歷右子樹。後序遍歷 先遍歷左子樹與右子樹,在遍歷根節點。因為有這樣...

前序 中序 後序遍歷

先序遍歷也叫做 先根遍歷 前序遍歷,可記做根左右 二叉樹父結點向下先左後右 首先訪問根結點然後遍歷左子樹,最後遍歷右子樹。在遍歷左 右子樹時,仍然先訪問根結點,然後遍歷左子樹,最後遍歷右子樹,如果二叉樹為空則返回。例如,下圖所示二叉樹的遍歷結果是 abdecf 中序遍歷首先遍歷左子樹,然後訪問根結點...