转自《Java程序员面试笔试宝典》(何昊等编著,机械工业出版社)
根据先序遍历和中序遍历,确定二叉树后,可以给出后序遍历或层序遍历。
/**
* 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(isEmpty(pre) || isEmpty(in) || pre.length != in.length){
return null;
}
return reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
public boolean isEmpty(int[] array){
if(array == null || array.length == 0){
return true;
}
return false;
}
public TreeNode reConstructBinaryTree(int[] pre, int s1, int e1, int[] in, int s2, int e2){
if(s1 > e1 || s2 > e2){
return null;
}
TreeNode root = new TreeNode(pre[s1]);
int index = findIndex(in, s2, e2, pre[s1]);
int offset = index - 1 - s2;
root.left = reConstructBinaryTree(pre, s1 + 1, s1 + 1 + offset, in, s2, s2 + offset);
root.right = reConstructBinaryTree(pre, s1 + 2 + offset, e1, in, s2 + offset + 2, e2);
return root;
}
public int findIndex(int[] a, int begin, int end, int n){
int result = 0;
if(isEmpty(a) || begin > end){
result = -1;
}else{
for(int i = begin; i <= end; i++){
if(a[i] == n){
result = i;
break;
}
}
}
return result;
}
}