参考思路:https://blog.csdn.net/qq_23217629/article/details/51718996?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
主要是采用递归的思想,还是需要多理解
/*
* 题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},
则重建二叉树并返回。
*
*
* 思路:使用递归,先找到根,将中序遍历分成左子树和右子树,
* 然后递归找到左右子树的root
* */
//树的定义
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class offer04 {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
//前序的第一个数定为根
TreeNode root=new TreeNode(pre[0]);
int len=pre.length;
//当只有一个节点的时候
if(len==1) {
root.left=null;
root.right=null;
return root;
}
//找到中序的节点的位置
int rootVal=root.val;
int i;
for(i=0;i<len;i++) {
if(rootVal==in[i]) {
break;
}
}
//左子树
if(i>0) {
int[] lpre=new int[i];
int[] lin=new int[i];
//初始化左子树的前序数组和中序数组
for(int j=0;j<i;j++) {
lpre[j]=pre[j+1];
}
for(int j=0;j<i;j++) {
lin[j]=in[j];
}
root.left=reConstructBinaryTree(lpre,lin);
}else {
root.left=null;
}
//右子树
if(len-i-1>0) {
int[] rpre=new int[len-i-1];
int[] rin=new int[len-i-1];
//初始化
for(int j=i+1;j<len;j++) {
rin[j-i-1]=in[j];
rpre[j-i-1]=pre[j];
}
root.right=reConstructBinaryTree(rpre,rin);
}else {
root.right=null;
}
return root;
}
}