树的广度优先搜索(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;
    }
}
相关推荐
彭于晏6897 分钟前
Android广播
android·java·开发语言
程序员-珍25 分钟前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
自由的dream1 小时前
0-1背包问题
算法
2401_857297911 小时前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
福大大架构师每日一题1 小时前
23.1 k8s监控中标签relabel的应用和原理
java·容器·kubernetes
金灰1 小时前
HTML5--裸体回顾
java·开发语言·前端·javascript·html·html5
菜鸟一皓1 小时前
IDEA的lombok插件不生效了?!!
java·ide·intellij-idea
爱上语文1 小时前
Java LeetCode每日一题
java·开发语言·leetcode
bug菌2 小时前
Java GUI编程进阶:多线程与并发处理的实战指南
java·后端·java ee
程序猿小D2 小时前
第二百六十九节 JPA教程 - JPA查询OrderBy两个属性示例
java·开发语言·数据库·windows·jpa