题解 | #求二叉树的层序遍历#

求二叉树的层序遍历

https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3

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>> levelOrder (TreeNode root) {
        Queue<TreeNode> que = new Queue<TreeNode>();
        List<List<int>> bigList = new List<List<int>>();
        if(root == null) return bigList;
        que.Enqueue(root);
        while(que.Count != 0){
            List<int> smallList = new List<int>();
            for(int len = que.Count; len > 0; len--){
                TreeNode cur = que.Dequeue();
                smallList.Add(cur.val);
                if(cur.left != null)que.Enqueue(cur.left);
                if(cur.right != null)que.Enqueue(cur.right);
            }
            bigList.Add(smallList);
        }
        return bigList;
    }
}

全部评论

相关推荐

07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
fRank1e:吓得我不敢去外包了,但是目前也只有外包这一个实习,我还要继续去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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