树的广度优先搜索(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;
    }
}
相关推荐
阳明山水8 分钟前
Mamba路径如何建模长程时序依赖
人工智能·深度学习·算法·机器学习·架构
technology_x16 分钟前
液冷超充站设备厂家哪家好?2026年功率与散热对比
java·开发语言
LayZhangStrive30 分钟前
Agent开发 - MCP Client使用MCP Server的几种方式(Spring AI)
java·spring ai·mcp
仓三43 分钟前
从 Prompt Engineering 到 Context Engineering:2026 年 Agent 性能提升的隐藏杠杆
java·prompt·context
许彰午1 小时前
07-SqlBuilder六法
java·开发语言·低代码·架构
孙6903421 小时前
Spring 注入多例 Bean
java·spring
Jul1en_1 小时前
【Java 脚手架】封装通用工具类-3
java·开发语言·redis·缓存·ai·bootstrap·rabbitmq
_Narcissus_1 小时前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治
明志数科1 小时前
具身智能数据工程全链路解析:从真实产线采集到LeRobot适配
网络·人工智能·算法
边境悍匪2 小时前
springboot常用注解
java·spring boot·学习