题目:
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
答案:
解法一:
递归的方法计算根节点的左右子树,代码如下:
注意Arrays.copyOfRange函数是左闭右开的。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre==null||in==null||pre.length==0||in.length==0){
return null;
}
TreeNode root = new TreeNode(pre[0]);
if(pre.length==1){
return root;
}
int root_index = arrayIndexOf(in,pre[0]);
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,1+root_index),Arrays.copyOfRange(in,0,root_index));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,root_index+1,pre.length),Arrays.copyOfRange(in,root_index+1,in.length));
return root;
}
public static int arrayIndexOf(int[] array,int target){
for(int i=0;i<array.length;i++){
if(array[i]==target){
return i;
}
}
return -1;
}
}