题解 | #重建二叉树#

重建二叉树

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

import java.util.Arrays;
import java.util.*;
public class Solution {
    static Map<Integer,Integer> map;
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length==0||in.length==0)return null;
        map=new HashMap<Integer,Integer>();
        int n=in.length;
        for(int i=0;i<n;i++){
            map.put(in[i],i);
        }
        TreeNode root=solveHelp(pre,0,n-1,in,0,n-1);
        return root;
    }
    // 构建树
    public static TreeNode solveHelp (int[] xianxu,int preLeft,int preRight,int[] zhongxu,int inLeft,int inRight) {
    	if(preLeft>preRight)return null;
        int in_root=map.get(xianxu[preLeft]);
        int left_nums=in_root-inLeft;
        TreeNode root=new TreeNode(xianxu[preLeft]);
        root.left=solveHelp(xianxu,preLeft+1,left_nums+preLeft,zhongxu,inLeft,in_root-1);
        root.right=solveHelp(xianxu,left_nums+preLeft+1,preRight,zhongxu,in_root+1,inRight);
        return root;
    }
}

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
今天投了小鹏,收到了AI面,大概会问哪些啊?
期末一定及格:总共4个部分,心理测评、行测、然后就是问岗位、对岗位的理解、过往遇到了哪些难点怎么解决,很简单,没有什么特别专业的问题,都是一些综合素质相关的
小鹏汽车AI面7人在聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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