树的广度优先搜索(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;
    }
}
相关推荐
+VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
需要8269 小时前
MySQL 索引 B+ 树与“查询为什么变慢了
java·spring boot·spring·spring cloud·tomcat
一 乐9 小时前
二手交易平台|基于springboot + vue二手交易平台(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序
万年咸鱼10 小时前
编译Java源程序
java
Wang's Blog10 小时前
Java 项目实战: 外卖平台-删除分类的关联校验与自定义业务异常
java·服务器·项目开发
INGNIGHT10 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法
hai_android10 小时前
Kotlin / Android 常用函数使用示例手册
android·java·kotlin
2401_8390805410 小时前
C++常见八股
数据结构·c++·算法
MayBaymax10 小时前
MongoDB 索引与事务
java·数据库·mongodb
vx-程序开发10 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django