输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
public class ReConstructBinaryTree {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0 || in.length == 0){
return null;
}
TreeNode treeNode = new TreeNode(pre[0]);
for(int i = 0;i<in.length;i++){
if(in[i] == pre[0]){
int[] str1 = new int[i];
int[] str2 = new int[i];
System.arraycopy(pre,1,str1,0,i);
System.arraycopy(in,0,str2,0,i);
treeNode.left = reConstructBinaryTree(str1,str2);
int[] str3 = new int[pre.length-1-i];
int[] str4 = new int[in.length - 1 -i];
System.arraycopy(pre,i+1,str3,0,pre.length - i -1);
System.arraycopy(in,i+1,str4,0,in.length - i -1);
treeNode.right = reConstructBinaryTree(str3,str4);
break;
}
}
return treeNode;
}
}