题解 | #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/**
- 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 [] vin) { return construct(pre, vin); }
public static TreeNode construct(int [] pre,int [] vin){
if(pre.length == 0){
return null;
}
if(pre.length == 1){
return new TreeNode(pre[0]);
}
int pos = find(vin, pre[0]);
int[] pre1 = Arrays.copyOfRange(pre, 1, pos+1);
int[] pre2 = Arrays.copyOfRange(pre, pos+1, pre.length);
int[] vin1 = Arrays.copyOfRange(vin, 0, pos);
int[] vin2 = Arrays.copyOfRange(vin, pos+1, pre.length);
TreeNode curHead = new TreeNode(pre[0]);
TreeNode left = construct(pre1, vin1);
TreeNode right = construct(pre2, vin2);
curHead.left = left;
curHead.right = right;
return curHead;
}
public static int find(int [] arr, int val){
for(int i=0;i<arr.length;i++){
if(arr[i]==val){
return i;
}
}
return 0;
}
}

查看9道真题和解析