题解 | #重建二叉树#
重建二叉树
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) {
//没什么好说的,参照评论区1楼大佬的代码,递归一定要注意return!!!
if(pre.length==0){
return null;
}
//找到root节点,
int rootVal = pre[0];
if(pre.length==1){
return new TreeNode(rootVal);
}
TreeNode root = new TreeNode(rootVal);
//确定左子树和右子树的位置
int rootIndex = 0;
for(int i=0;i<vin.length;i++){
if(rootVal == vin[i]){
rootIndex = i;
break;
}
}
//递归,假设root的左右子树已经构建完毕,将左右子树放到root左右即可
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,rootIndex+1),Arrays.copyOfRange(vin,0,rootIndex));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,rootIndex+1,pre.length),Arrays.copyOfRange(vin,rootIndex+1,vin.length));
return root;
}
}
海康威视公司福利 1235人发布
查看4道真题和解析