-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.cpp
62 lines (54 loc) · 1.56 KB
/
bfs.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Example program
#include <iostream>
#include <string>
#include <memory>
#include <list>
#include <vector>
#include <ostream>
struct Node{
Node(char val) : left(nullptr), right(nullptr), value(val) {}
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
char value;
};
using ListPtrs = std::list<std::shared_ptr<Node>>;
using VList = std::vector<ListPtrs>;
VList createLists(std::shared_ptr<Node> root) {
VList lists;
lists.push_back(ListPtrs{root});
for(std::size_t i = 0; i < lists.size(); i++) {
if(lists[i].size()) {
lists.push_back(ListPtrs());
}
for(auto& node : lists[i]) {
if(node->left != nullptr)
{
lists[i+1].push_back(node->left);
}
if(node->right != nullptr)
{
lists[i+1].push_back(node->right);
}
}
}
return lists;
}
int main()
{
std::shared_ptr<Node> root(new Node('a'));
root->left.reset(new Node('b'));
root->right.reset(new Node('c'));
root->left->left.reset(new Node('d'));
root->left->right.reset(new Node('e'));
root->right->left.reset(new Node('f'));
root->right->right.reset(new Node('g'));
root->left->right->left.reset(new Node('h'));
VList result = createLists(root);
for(auto& list : result){
if(list.size()) std::cout << "[";
for(auto &node : list) {
std::cout << node->value;
}
if(list.size()) std::cout << "]\n\n";
}
}