-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdfs_traversing.cpp
74 lines (65 loc) · 1.58 KB
/
dfs_traversing.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
67
68
69
70
71
72
73
74
#include "data_struct_types.h"
#include <vector>
#include <iostream>
#include <deque>
using namespace data_struct_types;
std::vector<int> output;
void TraverseDFS(BinaryTreeNode<int> *root)
{
if (root == nullptr)
{
return;
}
output.push_back(root->data);
TraverseDFS(root->left);
TraverseDFS(root->right);
}
void FastTraverseDFS(BinaryTreeNode<int> *root)
{
std::deque<BinaryTreeNode<int> *> stack;
if (root != nullptr)
{
stack.push_front(root);
}
while (!stack.empty())
{
auto node = stack.front();
stack.pop_front();
output.push_back(node->data);
if (node->right != nullptr)
{
stack.push_front(node->right);
}
if (node->left != nullptr)
{
stack.push_front(node->left);
}
}
}
int main(int argc, char const *argv[])
{
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(0);
root->left = new BinaryTreeNode<int>(1);
root->right = new BinaryTreeNode<int>(2);
root->left->left = new BinaryTreeNode<int>(3);
root->left->right = new BinaryTreeNode<int>(4);
output.clear();
TraverseDFS(root);
std::cout << "Recursive version:" << std::endl;
std::cout << "[";
for (auto data : output)
{
std::cout << data << ",";
}
std::cout << "]" << std::endl;
output.clear();
FastTraverseDFS(root);
std::cout << "Normal version:" << std::endl;
std::cout << "[";
for (auto data : output)
{
std::cout << data << ",";
}
std::cout << "]" << std::endl;
return 0;
}