题解 | #从下到上打印二叉树#

从下到上打印二叉树

https://www.nowcoder.com/practice/ed982e032ff04d6a857b4cb4e6369d04

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 root TreeNode类
     * @return int整型二维数组
     */
    public List<List<int>> levelOrderBottom (TreeNode root) {
        // write code here
        if (root == null)
            return null;
        List<List<int>> lslsN = new List<List<int>>();
        lslsN.Add(new List<int>() {
            root.val
        });
        GDBL(root, ref lslsN, 1);
        for (int nIndex = lslsN.Count - 1; nIndex >= 0; nIndex--) {
            if (lslsN[nIndex].Count != 0)
                continue;
            lslsN.RemoveAt(nIndex);
        }
        lslsN.Reverse();
        return lslsN;
    }

    public static void GDBL(TreeNode root, ref List<List<int>> lslsN, int nCurH) {
        // write code here
        if (root.left == null && root.right == null)
            return;
        List<int> lsN = new List<int>();
        lslsN.Add(lsN);
        if (root.left != null) {
            lslsN[nCurH].Add(root.left.val);
            GDBL(root.left, ref lslsN, nCurH + 1);
        }
        if (root.right != null) {
            lslsN[nCurH].Add(root.right.val);
            GDBL(root.right, ref lslsN, nCurH + 1);
        }
    }
}

全部评论

相关推荐

10-16 15:48
算法工程师
点赞 评论 收藏
分享
10-22 12:03
山东大学 Java
程序员小白条:26届一般都得有实习,项目可以随便写的,如果不是开源社区的项目,随便包装,技术栈也是一样,所以本质应该找学历厂,多投投央国企和银行,技术要求稍微低一点的,或者国企控股那种,纯互联网一般都得要干活
应届生简历当中,HR最关...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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