package offerAnswer;
/* 定义二叉树*/
public class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
package OfferAnswer;
/**
* 面试题6
* 重建二叉树
* @author lwk
* 1.通过前序遍历确定根节点
* 2.在中序遍历找到该节点,那么在该节点前面的为左子树的节点,该节点后面的为右子树的节点
* 3.递归
*/
public class Answer06 {
public static void main(String[] args) {
int[] pre={1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
BinaryTreeNode root = reconstructBinaryTree(pre,in);
BinaryTreeNode p = root;
while(null != p){
System.out.println(p.value);
p = p.left;
}
}
public static BinaryTreeNode reconstructBinaryTree(int[] pre, int[] in){
if(pre == null || pre.length == 0 || in == null || in.length == 0){
return null;
}
return reconstructBinaryTree(pre,0,in,0,pre.length-1);
}
public static BinaryTreeNode reconstructBinaryTree(int[] pre, int preStart, int[] in, int inStart, int inEnd){
if(inStart > inEnd){
return null;
}
BinaryTreeNode root = new BinaryTreeNode();
root.value = pre[preStart];
if(inStart == inEnd){
return root;
}
//在中序遍历中寻找根节点
int i = inStart;
for (i = inStart; i < in.length; i++) {
if(in[i] == root.value){
break;
}
}
//下标i即为根节点的位置
//一分为二,寻找子数组的根节点,分别为该根节点的左右子节点
root.left = reconstructBinaryTree(pre, preStart+1 , in, inStart, i-1);
root.right = reconstructBinaryTree(pre, i-inStart+preStart+1, in, i+1, inEnd);
return root;
}
}