[AlgoExpert] Breadth First Search

Breadth First Search

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Node {
public:
string name;
vector<Node *> children;

Node(string str) { name = str; }

vector<string> breadthFirstSearch(vector<string> *array) {
queue<Node*> q;
q.push(this);
while(!q.empty()) {
auto node = q.front(); q.pop();
array->push_back(node->name);
for(auto& child : node->children) {
q.push(child);
}
}
return *array;
}

Node *addChild(string name) {
Node *child = new Node(name);
children.push_back(child);
return this;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/16/PS/AlgoExpert/breadth-first-search/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.