题解 | #重建二叉树#

重建二叉树

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

using System;
using System.Collections.Generic;

/*
public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode (int x)
    {
        val = x;
    }
}
*/

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pre int整型一维数组 
     * @param tin int整型一维数组 
     * @return TreeNode类
     */
    public TreeNode reConstructBinaryTree (List<int> pre, List<int> vin) {
        // write code here
        if (pre.Count > 0 && vin.Count > 0){
            TreeNode root = new TreeNode(pre[0]);
            List<int> preLeftList = new List<int>();
            List<int> vinLeftList = new List<int>();
            List<int> preRightList = new List<int>();
            List<int> vinRightList = new List<int>();
            int rootIndex = vin.IndexOf(pre[0]);
            // 拆分前序序列
            for(int i=1; i< pre.Count; i++){
                if(i<=rootIndex){
                    preLeftList.Add(pre[i]);
                }else{
                    preRightList.Add(pre[i]);
                }
            }
            // 拆分中前序序列
            for(int i=0; i< vin.Count; i++){
                if(i<rootIndex){
                    vinLeftList.Add(vin[i]);
                }else if(i>rootIndex){
                    vinRightList.Add(vin[i]);
                }
            }
            root.left = reConstructBinaryTree(preLeftList, vinLeftList);
            root.right = reConstructBinaryTree(preRightList, vinRightList);
            return root;
        }else{
            return null;
        }
        
    }
}
全部评论

相关推荐

07-02 13:50
闽江学院 Java
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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