day-23 N 叉树的层序遍历

思路:利用bfs,利用队列将当前层的孩子元素加入队列,再将本层元素出队即可

注意点:res.remove()执行后,ArrayList的元素索引会改变,可以先添加下一层所有元素后,再将本层元素一起出队

code:

java 复制代码
/*
// 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<List<Integer>>();
        if(root==null)return res;
        List<Node> now=new ArrayList<Node>();
        now.add(root);
        while(now.size()>0){
            int num=now.size();
            List<Integer> t=new ArrayList<Integer>();
            for(int i=0;i<num;i++){//遍历同一层元素
                t.add(now.get(i).val);
                int cur=now.get(i).children.size();
                for(int j=0;j<cur;j++){//遍历每个元素的孩子
                    if(now.get(i).children.get(j)!=null){
                        now.add(now.get(i).children.get(j));
                    }
                }
            }
            for(int i=0;i<num;i++){
                now.remove(0);
            }
            res.add(t);
        }
        return res;
    }
}
相关推荐
shehuiyuelaiyuehao17 小时前
算法31,前缀和,可被k整除的子数组
数据结构·python·算法
203号居民19 小时前
LeetCode hot 100 — 141. 环形链表2
算法·leetcode·链表
玖玥拾19 小时前
LeetCode 202 快乐数
算法·leetcode
LuminousCPP19 小时前
数据结构-二叉树(六):BFS层序遍历与完全二叉树判断|复用链式队列 + (N_0=N_2+1) 性质证明
c语言·数据结构·笔记·算法·二叉树·宽度优先
ZhouDevin20 小时前
算法论文/数据集3——CLD(TMLR2025)压缩训练集,仅保留对验证集有益的样本
人工智能·深度学习·算法·计算机视觉
Tim_1021 小时前
【LeetCode】29、两数相除
算法·leetcode·职场和发展
船厂电气自动化ai大模型21 小时前
AI大模型与数学/第63课:矩阵定义、矩阵加法、标量乘法(逐级精讲)
数据结构·人工智能·深度学习·线性代数·算法
余额瞒着我当琳1 天前
算法修炼 chapter 2 双指针进阶、盛最多水的容器、有效三角形的个数、两数之和、三数之和、四数之和
算法
你压到我腿毛了6661 天前
C语言冒泡算法(Bubble sort)
c语言·数据结构·算法
靠沿1 天前
贪心算法专题(三)
算法·贪心算法