题目:给定一颗二叉树的前序和中序遍历结果,重构该二叉树,并输入其头结点
package offer;
public class offer6_ReBuildTree {
/**
* 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树,并输出其头结点。
* 假设输入的两种遍历结果中都不含重复的数字
* @param args
*/
public static void main(String[] args) {
int[] pre = {1,2,3,4,5,6,7};
int[] in = {3,2,4,1,6,5,7};
TreeNode root = offer6_ReBuildTree.reConstructBinaryTree(pre,in);
}
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre == null || in == null){
return null;
}
TreeNode root = reBuildTree1(pre, 0, pre.length-1, in, 0, in.length-1);
return root;
}
/**
* 第一种
* @param pre
* @param preStart
* @param preEdn
* @param in
* @param inStart
* @param inEdn
* @return
*/
public static TreeNode reBuildTree1(int[] pre,int preStart,int preEdn,int[] in,int inStart,int inEdn){
if(inStart > inEdn || preStart>preEdn){
return null;
}
TreeNode node = new TreeNode(pre[preStart]);
preStart++;
while(in[inStart] != node.val && inStart<inEdn){
inStart++;
}
node.left = reBuildTree1(pre, preStart, inStart, in, preStart-1,inStart);
node.right = reBuildTree1(pre, inStart+1, pre.length-1, in, inStart+1, in.length-1);
return node;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int x) {
val = x;
}
}
}