题目:
题目链接
解法:
对于先序序列,第一个节点为根节点。对应中序序列中该节点的位置,则左边为左子树,右边为右子树。对于左子树和右子树重复上面的过程,即一个递归的过程。这里先将中序序列中每个节点对应的下标存在HashMap中方便查找。
图解:
以第一个节点为例,我们找到3在中序序列中的位置,然后将先序序列和中序序列都切割成左右子树,找到对应的下标,递归求解即可。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private HashMap<Integer,Integer> map;
public TreeNode createTree(int[] preorder, int[] inorder,int pre_left,int pre_right,int in_left,int in_right){
if(pre_left>pre_right){
return null;
}
int root_val=preorder[pre_left];
TreeNode root=new TreeNode(root_val);
int mid=map.get(root_val);
int mid_pre=mid-in_left;
root.left=createTree(preorder,inorder,pre_left+1,pre_left+mid_pre,in_left,mid-1);
root.right=createTree(preorder,inorder,pre_left+1+mid_pre,pre_right,mid+1,in_right);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
map=new HashMap<>();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return createTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}
}