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

2021-10-25 07:26:51 字數 1054 閱讀 9325

* definition for a binary tree node.

* public class treenode 

class solution {

public treenode buildtree(int preorder, int inorder) {

return buildtreehelper(preorder,0,preorder.length,inorder,0,inorder.length);

//左閉右開

public treenode buildtreehelper(int preorder, int p_start,int p_end,int inorder,int i_start,int i_end){

//判空

if (p_start == p_end) {

return null;

//獲取前序的根節點值

int root_val=preorder[p_start];

treenode root=new treenode(root_val);

//每次中序根節點位置

int i_root_idx=0;

for(int i=i_start;iif(root_val==inorder[i]){

i_root_idx=i;

break; 

int i_plus=i_root_idx-i_start;  //每次根節點和左面距離,eg 0,2

//遞迴的構造左子樹,前序從第二個開始,第乙個寫好了第二個直接寫

//注意邊界,左閉右開,跳過根節點

root.left=buildtreehelper(preorder,p_start+1,p_start+i_plus+1,

inorder,i_start,i_root_idx);

//遞迴的構造右子樹

root.right=buildtreehelper(preorder,p_start+i_plus+1,p_end,

inorder,i_root_idx+1,i_end);

return root;

還需優化map

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

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

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

如題,根據前序與中序遍歷序列構造二叉樹 整體思路 前序遍歷的第乙個元素,必然是二叉樹的根節點 在中序遍歷中找到前序遍歷第乙個元素的位置 該位置左邊的所有點都是二叉樹的左子樹元素,該位置右邊的所有點都是二叉樹的右子樹元素 思路一 遞迴 字典 由整體思路可以構建子函式用於遞迴,不斷求子樹的左右子樹,直到...

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

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