题解 | #把二叉树打印成多行#

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

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 pRoot TreeNode类
     * @return int整型二维数组
     */
    public List<List<int>> Print (TreeNode pRoot) {
        // write code here
        if (pRoot == null)
            return new List<List<int>>();
        return PrintGD(new List<TreeNode>() {
            pRoot
        });
    }

    public List<List<int>> PrintGD(List<TreeNode> lT) {
        // write code here
        if (lT == null || lT.Count == 0)
            return null;
        List<List<int>> lsls = new List<List<int>>();
        List<int> ls = new List<int>();
        List<TreeNode> lTNew = new List<TreeNode>();
        for (int i = 0; i < lT.Count; i++) {
            ls.Add(lT[i].val);
            if (lT[i].left != null)
                lTNew.Add(lT[i].left);
            if (lT[i].right != null)
                lTNew.Add(lT[i].right);
        }
        if (ls.Count != 0)
            lsls.Add(ls);
        List<List<int>> lslsC = PrintGD(lTNew);
        if (lslsC != null && lslsC.Count != 0)
            lsls.AddRange(lslsC);
        return lsls;
    }
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务