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

2021-10-03 05:58:11 字數 1718 閱讀 3343

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

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

例如,給出

前序遍歷 preorder = [3,9,20,15,7]

中序遍歷 inorder = [9,3,15,20,7]

返回如下的二叉樹:
3

/ \9 20

/ \

15 7

python
# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class

solution

:def

buildtree

(self, preorder, inorder)

:"""

:type preorder: list[int]

:type inorder: list[int]

:rtype: treenode

"""defhelper

(in_left =

0, in_right =

len(inorder)):

nonlocal pre_idx

# if there is no elements to construct subtrees

if in_left == in_right:

return

none

# pick up pre_idx element as a root

root_val = preorder[pre_idx]

root = treenode(root_val)

# root splits inorder list

# into left and right subtrees

index = idx_map[root_val]

# recursion

pre_idx +=

1# build left subtree

root.left = helper(in_left, index)

# build right subtree

root.right = helper(index +

1, in_right)

return root

# start from first preorder element

pre_idx =

0# build a hashmap value -> its index

idx_map =

return helper(

)

/**

* definition for a binary tree node.

* struct treenode

* };

*/class

solution

treenode*

buildtree

(vector<

int>

& preorder, vector<

int>

& inorder)

};

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

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

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

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

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

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。解題思路 left,right 這個區間就表示當前preorder index 這個結點對應的子樹的中序遍歷結果 private treenode buildtreehelper int preorder,int inorder,int left,int r...