《剑指offer》----重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路
前序遍历的数组中第一个值一定是根结点(根结点->左结点->右结点),该结点对应到中序遍历中,该结点在中序遍历对应的位置能将其分成左子树和右子树,如{1,2,4,7,3,5,6,8},1肯定为根结点,对应到{4,7,2,1,5,3,8,6}中,{4,7,2}为{1}的左子树和{5,3,8,6}为{1}的右子树,如此不断用中序遍历定位左右子树,InL用来记录中序遍历数组中左右子树的起始位置,根结点的位置减去InL便可以得到左右子树的大小,再根据先序遍历的数组便可重构二叉树
源码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Map;
import java.util.HashMap;
public class Solution {
Map<Integer,Integer> inPosition= new HashMap<Integer,Integer>();
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
for(int i=0;i<in.length;i++){
inPosition.put(in[i],i);
}
return reConstruct(pre,0,pre.length-1,0);
}
public TreeNode reConstruct(int[] pre,int preL,int preR,int inL){
if(preL>preR){
return null;
}
TreeNode root=new TreeNode(pre[preL]);
int inForPrePosition = inPosition.get(root.val);
int leftTreeSize = inForPrePosition-inL;
root.left=reConstruct(pre,preL+1,preL+leftTreeSize,inL);
root.right=reConstruct(pre,preL+leftTreeSize+1,preR,inL+leftTreeSize+1);
return root;
}
}