题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
int length = pre.length - 1;
return recursion(pre, 0, length, in, 0, length);
}
public TreeNode recursion(int [] pre, int preL, int preR, int [] in, int inL, int inR) {
int val = pre[preL];
TreeNode node = new TreeNode(val);
if(preL == preR) {
node.left = null;
node.right = null;
return node;
}
int i = inL;
for(; i <= inR; i++) {
if(in[i] == val){
break;
}
}
int distance = i - inL;
if(distance > 0)
node.left = recursion(pre, preL + 1, preL + distance, in, inL, i - 1);
if(distance < preR - preL)
node.right = recursion(pre, preL + distance + 1, preR, in, i + 1, inR);
return node;
}
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};
Solution obj = new Solution();
obj.reConstructBinaryTree(pre, in);
}
}