题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},重建出下图所示的二叉树并输出它的头结点。
package leecode;
import java.util.Arrays;
public class BinaryTreePrint {
public static void main(String[] args) throws Exception {
int[] preSort = { 1, 2, 4, 7, 3, 5, 6, 8 };
int[] inSort = { 4, 7, 2, 1, 5, 3, 8, 6 };
BinaryTreeNode root = constructCore(preSort, inSort);
System.out.println();
System.out.print(root.value+",");
print(root);
}
public static void print(BinaryTreeNode root){
if (root==null) {
return ;
}
if (root.left!=null) {
System.out.print(root.left.value+",");
}
if (root.right!=null) {
System.out.print(root.right.value+",");
}
print(root.left);
print(root.right);
}
public static BinaryTreeNode constructCore(int[] pre,int[] in){
if (pre==null||in==null||pre.length==0||in.length==0||in.length!=pre.length) {
return null;
}
BinaryTreeNode root=new BinaryTreeNode();
for (int i = 0; i < in.length; i++) {
if (in[i]==pre[0]) {
root.value=in[i];
System.out.print(root.value+",");
root.left=constructCore(Arrays.copyOfRange(pre, 1, i+1),Arrays.copyOfRange(in, 0,i));
root.right=constructCore(Arrays.copyOfRange(pre, i+1,pre.length),Arrays.copyOfRange(in,i+1, in.length));
}
}
return root;
}
}
class BinaryTreeNode {
public int value;
public BinaryTreeNode left;
public BinaryTreeNode right;
}