树的广度优先搜索(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;
    }
}
相关推荐
石去皿3 分钟前
力扣hot100 91-100记录
算法·leetcode·职场和发展
264玫瑰资源库1 小时前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
SsummerC2 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
pwzs2 小时前
Java 中 String 转 Integer 的方法与底层原理详解
java·后端·基础
东阳马生架构2 小时前
Nacos简介—2.Nacos的原理简介
java
普if加的帕2 小时前
java Springboot使用扣子Coze实现实时音频对话智能客服
java·开发语言·人工智能·spring boot·实时音视频·智能客服
爱喝一杯白开水2 小时前
SpringMVC从入门到上手-全面讲解SpringMVC的使用.
java·spring·springmvc
王景程2 小时前
如何测试短信接口
java·服务器·前端
2301_807611492 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
zhang23839061543 小时前
IDEA add gitlab account 提示
java·gitlab·intellij-idea·idea