• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
广度优先搜索 BFS
广度优先搜索,队列

1. 问题描述

使用广度优先搜索遍历树,输出一个结果保存在数组中。

2. 分析

  1. 加入新结点到队列中
  2. pop一个结点,加入到结果数组中
  3. append当前结点的所有孩子结点到队列中
  4. 重复2-3
  • 什么时候停?当队列中所有的结点都被pop完毕。

3. 代码

时间复杂度: O(V+E)

空间复杂度: O(V) 当孩子结点都在Level 1 上的时候,我们需要把 V-1个孩子结点一起加入队列中。

class Node:
    def __init__(self, name):
        self.children = []
        self.name = name

    def addChild(self, name):   //O(E) edges are the number of childern
        self.children.append(Node(name))
        return self

    def breadthFirstSearch(self, array):  // O(V) 
        queue = [self]
        while len(queue)>0:
            curr = queue.pop(0)
            array.append(curr.name) # append the curr.name, not just curr
            for child in curr.children:
                queue.append(child)
        return array
import java.util.*;

class Program {
  static class Node {
    String name;
    List<Node> children = new ArrayList<Node>();

    public Node(String name) {
      this.name = name;
    }

    public List<String> breadthFirstSearch(List<String> array) {
      Queue<Node> queue = new LinkedList<Node>();
            queue.add(this);
            while(!queue.isEmpty()){
                Node curr = queue.poll();
                array.add(curr.name);
                queue.addAll(curr.children);
            }
      return array;
    }

    public Node addChild(String name) {
      Node child = new Node(name);
      children.add(child);
      return this;
    }
  }
}

 

posted on 2021-01-07 13:21  LilyLiya  阅读(76)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3