给出一棵二叉树的前序遍历序列和中序遍历序列,要求: 生成这棵二叉树
思路:二叉树一般使用递归的思想,在这里使用前序遍历的方式生成这棵树。先根据前序遍历序列得到根节点,然后在中序遍历序列中找到这个根节点,根节点左边的是左子树中序序列,右边的是右子树中序序列,然后分别构造左子树和右子树。
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
return createTree(pre, in, 0, pre.length-1, 0, in.length-1);
}
public TreeNode createTree(int [] pre, int [] in, int f1, int t1, int f2, int t2) {
if(f1 <= t1 && f2 <= t2) {
TreeNode root = new TreeNode(pre[f1]);
int len = find(in, pre[f1]);
root.left = createTree(pre, in, f1 + 1, f1 + len - f2, f2, len - 1);
root.right = createTree(pre, in, f1 + len - f2 + 1, t1, len + 1, t2);
return root;
}
return null;
}
public int find(int [] in, int x) {
for(int i = 0; i < in.length; i++) {
if(x == in[i]) {
return i;
}
}
return 0;
}
}