AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 商店
  • 应用
  • 文章
    • 题解
    • 分享
    • 问答
  • 吐槽
  • 登录/注册

LeetCode 429. N叉树的层序遍历    原题链接    中等

作者: 作者的头像   Acwer ,  2022-08-06 14:57:17 ,  所有人可见 ,  阅读 9


0


解题思路

广度优先搜索模板题。

广度优先搜索模板

广度优先遍历:

储存遍历结果:List<Integer> res

队列:queue

queue.add(root.val);      //把第一层元素放入到队列中

while(queue.size()!=0){

​           int length = queue.size();

​            List<Integer> level;         //储存这一层所有元素。

​           for(int i=0;i<length;i++){

​                   node = queue.poll();   //得到队头,同时丢去队头

​                   //把temp扩展的下一层元素都放到队列queue中

​                   if(node.left!=null){}          

​                   if(node.right!=null){}

​                   //储存上一层的所有节点

​                   level.add(templ);

​           }   

​           res.add(level);

}

相关代码

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<Node> queue = new LinkedList<>();
        if(root==null) return res;
        queue.add(root);
        while(queue.isEmpty()==false){
            int len = queue.size();
            List<Integer> level = new ArrayList<>();
            for(int i=0;i<len;i++){
                Node temp = queue.poll();
                for(int j=0;j<temp.children.size();j++){
                    queue.add(temp.children.get(j));
                }
                level.add(temp.val);
            }     
            res.add(level);
        }
        return res;
    }
}

0 评论

你确定删除吗?
1024
x

© 2018-2022 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息