题解 | #重建二叉树#

重建二叉树

https://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
        int n = pre.Count;
        int m = vin.Count;
        if (m == 0 || n == 0)
            return null;
        TreeNode root = new TreeNode(pre[0]);
        for (int i = 0; i < vin.Count; i++) {
            if (pre[0] == vin[i]) {
                List<int> leftpre = new List<int>(pre.GetRange(1, i));
                List<int> leftvin = new List<int>(vin.GetRange(0, i));
                root.left = reConstructBinaryTree(leftpre, leftvin);

                List<int> rightpre = new List<int>(pre.GetRange(i + 1, vin.Count - (i + 1)));
                List<int> rightvin = new List<int>(vin.GetRange(i + 1, vin.Count - (i + 1)));
                root.right = reConstructBinaryTree(rightpre, rightvin);
            }
        }
        return root;
    }
}

全部评论

相关推荐

Aurora23:属于挂一半,暂时进池子了,隔一段时间没有其他组捞的话就彻底结束了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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