题目的意思是,给你一个前序遍历的结果和一个中序遍历的结果,让你恢复原来的二叉树。
学过数据结构的我们知道,前序和中序可以求出原来的二叉树,后续和中序也可以,但是前序和后序是不可以的。
解题的大致思路是:前序的第一个,就是根。在中序中找到这个数,这个数左边的是左子树,右边的是右子树。相信这个在数据结构中大家都学习过了。现在要做的就是根据这个思想,重建二叉树。细节就不多说了,看代码。下载地址:http://download.csdn.net/detail/worsun/9314853
下面是我的代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(0 == pre.length){//如果没有数据
return null;
}else if(1 == pre.length){//只有一个数据
TreeNode node = new TreeNode(pre[0]);
node.left = null;
node.right = null;
return node;
}else{
TreeNode root = new TreeNode(pre[0]);
int mid = findLocation(pre[0], in);//找到pre中第一个数在in中的位置
//以下是将数据分成两部分,一部分是左边的,一部分是右边的
int[] lpre = new int[mid];
int[] lin = new int[mid];
int[] rpre = new int[pre.length - mid - 1];
int[] rin = new int[pre.length - mid - 1];
for(int i = 0; i < mid; i ++){
lpre[i] = pre[i + 1];
lin[i] = in[i];
}
int m = mid + 1;
for(int i = 0; i < pre.length - mid - 1; i++, m++){
rpre[i] = pre[m];
rin[i] = in[m];
}
//递归的进行求左边和右边
root.left = reConstructBinaryTree(lpre, lin);
root.right = reConstructBinaryTree(rpre, rin);
return root;
}
}
public int findLocation(int index, int [] in){
int i = 0;
while(index != in[i]){
i++;
}
return i;
}
}
看到别人写的代码,思路一样,但是比我的简单,贴出来一起学习吧
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
return root;
}
//前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
if(startPre>endPre||startIn>endIn)
return null;
TreeNode root=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;i++)
if(in[i]==pre[startPre]){
root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
}
return root;
}
}