题解 | #重建二叉树#
重建二叉树
http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
参考的一个大佬的思想,真的太清晰了
import java.util.Arrays;
/**
* 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 (pre.length == 0 || in.length == 0) {//特殊情况特殊讨论
return null;
}
TreeNode root = new TreeNode(pre[0]);//确定根节点
int index=getRootindex(pre,in);
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,index+1),Arrays.copyOfRange(in,0,index));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,index+1,pre.length),Arrays.copyOfRange(in,index+1,in.length));
return root;
}
public int getRootindex(int[] pre,int[] mid){
for(int i=0;i<mid.length;i++){
if(mid[i]==pre[0]){
return i;
}
}
return 0;
}
}
查看11道真题和解析