forked from rudi8848/data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.1.tree_traversal.cpp
More file actions
63 lines (58 loc) · 1.04 KB
/
4.1.tree_traversal.cpp
File metadata and controls
63 lines (58 loc) · 1.04 KB
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
#include <iostream>
#include <vector>
struct Node
{
int val;
int left;
int right;
};
class Tree
{
public:
Tree(int n) {
_tree.resize(n);
int val, left, right;
for (int i = 0; i < n; ++i) {
std::cin >> val >> left >> right;
_tree[i].val = val;
_tree[i].left = left;
_tree[i].right = right;
}
}
~Tree() {}
void printInOrder(int v) {
if (v == -1)
return;
printInOrder(_tree[v].left);
std::cout << _tree[v].val << " ";
printInOrder(_tree[v].right);
}
void printPreOrder(int v) {
if (v == -1)
return;
std::cout << _tree[v].val << " ";
printPreOrder(_tree[v].left);
printPreOrder(_tree[v].right);
}
void printPostOrder(int v) {
if (v == -1)
return;
printPostOrder(_tree[v].left);
printPostOrder(_tree[v].right);
std::cout << _tree[v].val << " ";
}
private:
std::vector<Node> _tree;
};
int main(void) {
int n;
std::cin >> n;
Tree tree(n);
tree.printInOrder(0);
std::cout << std::endl;
tree.printPreOrder(0);
std::cout << std::endl;
tree.printPostOrder(0);
std::cout << std::endl;
return 0;
}