树的广度优先搜索(java实现)

树的广度优先搜索是指从左往右,从上到下层序遍历树中的节点。

想要使用java实现广度优先搜索可以使用队列来实现。

首先将根节点放入队列,代表该树的第一层入队。随后进入循环,每次循环都将下一层的所有节点放入队列。具体做法为每次循环中先记录下当前队列中有几个节点,也就是该层的节点数。

然后将队列中的所有节点分别将出队,出队时让其子节点入队,这样当所有节点都出队时,其下一层所有的子节点也就入队了。这样循环往复知道队列为空为止,因为队列为空就代表已经到达最后一层,已经遍历完毕。

例如,假如现有如下多叉树

首先把根节点放入队列,其有三个子节点

随后将根节点出队,进入结果中,将子节点入队,至此树的第一层遍历完毕

随后将2出队,加入结果中,2出队时5和6入队

再将3,4出队放入结果中,将7入队,至此树的第二层遍历完毕

最后将567依次出队放入结果,至此整棵树遍历完毕

具体例题见力扣第429题------N叉树的层序遍历

题解如下:

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;
        }
        Queue<Node> queue = new ArrayDeque<Node>();
        //放入根节点
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> curres = new ArrayList<Integer>();
            int l = queue.size();
            for(int i =0;i<l;i++){
                //节点出队
                Node c = queue.poll();
                curres.add(c.val);
                for(Node c2:c.children){
                    //节点入队
                    queue.add(c2);
                }
            }
            //将该层所有节点放入结果数组
            res.add(curres);
        }
        return res;
    }
}
相关推荐
头发还在的女程序员12 小时前
医院陪诊管理系统怎么选择?——2026 年选型避坑与架构参考
java·开发语言·陪诊系统·陪诊app·医院陪诊陪护
CodeStats12 小时前
【Spring事务】Spring事务注解 @Transactional 完整体系:从 MySQL 隔离级别到 MyBatis 原理详解
java·spring·mybatis·事务·transactional
我命由我1234513 小时前
Android 开发问题:为 PDFView 设置一个带有黑色边框的背景 drawable,但边框没有生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
拳里剑气13 小时前
C++算法:BFS解决FloodFill算法
c++·算法·bfs·宽度优先
都叫我大帅哥15 小时前
从Python到Java:为什么企业级Agent最终会选择Java?
java·ai编程
wanderist.15 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
稚南城才子,乌衣巷风流16 小时前
支配树(Dominator Tree)详解:概念、算法与应用
算法
稚南城才子,乌衣巷风流16 小时前
动态开点:原理、实现与应用场景
数据结构·算法
yyds_yyd_1008616 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode