根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/
9 20
/
15 7
只能从前序中序或或 中序后序遍历构建,思路很简单就是扣细节,难得扣
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map <Integer,Integer> map=new HashMap<>();//存储中序遍历中的索引
public TreeNode robot(int[] preorder,int preL,int preR,int inL){
if(preL>preR)
return null;
//先算好找到根的各个位置
TreeNode root=new TreeNode(preorder[preL]);
int index=map.get(root.val);//拿到对应的中序遍历的下标,方便算左右子树在数组的距离
int lefttreesize=index-inL;
root.left=robot(preorder,preL+1,lefttreesize+preL,inL);
root.right=robot(preorder,preL + lefttreesize + 1, preR, inL + lefttreesize + 1);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
//仿照大神先来个hashmap放中序遍历的索引
for(int i=0;i<inorder.length;i++)
map.put(inorder[i],i);
return robot(preorder,0,preorder.length-1,0);
}
}