题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

import java.util.*; 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 [] vin) {
    if(pre.length == 0 && vin.length == 0){
        return null;
    }
    //头节点
    TreeNode pRoot = new TreeNode(pre[0]);
    //递归解决
    for(int i = 0; i < vin.length; i++){
        if(pre[0] == vin[i]){
            pRoot.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(vin, 0, i));
            pRoot.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, vin.length), Arrays.copyOfRange(vin, i + 1, vin.length));
        }
    }
    return pRoot;
}

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
06-23 17:45
门头沟学院 Java
里面的项目啥的真的有用吗?&nbsp;这些人是割韭菜吗?
HellowordX:很简单,如果你有自己稳定的学习路线和获取知识的方式就没必要,如果你啥都不懂的小白或者里边有你感兴趣的知识,我觉得挺值,我也经常为知识付费,因为时间精力有限,很多东西我不可能自己重复造轮子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务