-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs-vs-dfs.cpp
66 lines (56 loc) · 1.17 KB
/
bfs-vs-dfs.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
63
64
65
66
#include <bits/stdc++.h>
template <typename Node>
void visit(Node node) {
std::cerr << node->data << std::endl;
}
template <typename Node>
void bfs(Node root) {
std::queue<Node> nodes;
nodes.push(root);
while (!nodes.empty()) {
auto node = nodes.front();
nodes.pop();
visit(node);
if (node->left) {
nodes.push(node->left);
}
if (node->right) {
nodes.push(node->right);
}
}
}
/*
only change queue for stack and the order in which the nodes are pushed
*/
template <typename Node>
void dfs(Node root) {
std::stack<Node> nodes;
nodes.push(root);
while (!nodes.empty()) {
auto node = nodes.top();
nodes.pop();
visit(node);
if (node->right) {
nodes.push(node->right);
}
if (node->left) {
nodes.push(node->left);
}
}
}
// see https://github.com/whoan/snip
// snip("cpp/binary-search-tree.hpp")
/*
6
4 2 7 1 3 6
*/
int main() {
std::size_t numberOfElements;
std::cin >> numberOfElements;
auto binarySearchTree = snip::createBinarySearchTreeFromInput(numberOfElements);
auto root = binarySearchTree.getRoot();
bfs(root);
std::cerr << std::endl << std::endl;
dfs(root);
return 0;
}