题解 | #重建二叉树#

重建二叉树

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;
    }
}

全部评论

相关推荐

我:“加班需要有加班工资。”&nbsp;hr:“为什么?”&nbsp;哈哈哈哈哈哈哈离大谱
juntenor:你确实太理想化了,对社会不了解呀。这个和HR没有关系,这是国内特色,不然怎么还会有外包就这种逆天的存在呢。
点赞 评论 收藏
分享
06-16 15:04
黑龙江大学 Java
零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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