-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmake_tree.cpp
116 lines (95 loc) · 2.22 KB
/
make_tree.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <iostream>
#include <signal.h>
#include <vector>
#include <map>
using namespace std;
//global enteties
bool interrupt_raised = 0;
typedef struct Node {
int value;
Node* left = NULL;
Node* right = NULL;
} Node;
map <int, vector<int> > tree;
//functions
void display_tree()
{
for (map<int, vector<int> >::iterator it=tree.begin(); it != tree.end(); ++it ){
cout << "Depth = " << it->first << ": ";
for(vector<int>::const_iterator v=(it->second).begin(); v != (it->second).end(); ++v )
cout << *v << ", ";
cout << endl;
}
}
void print_tree(Node* head, int depth)
{
cout << "Depth=" << depth+1 << ": ";
while ( head != NULL ) {
//cout << "PRINT_TREE " << "head address " << head << endl;
cout << head->value << endl;
tree[depth+1].push_back(head->value);
if (head->left != NULL) {
cout << "Left: " ;
print_tree(head->left, depth+1);
}
if (head->right != NULL) {
cout << "Right: " ;
print_tree(head->right, depth+1);
}
return;
}
}
void build_tree(Node* head, int value)
{
//cout << "address of head node:" << head << endl;
if ( value < head->value ) {
if (head->left == NULL) {
head->left = new Node;
head->left->value = value;
head->left->left = NULL;
head->left->right = NULL;
//cout << head->left << " and value =" << head->left->value << endl;
} else {
build_tree(head->left, value);
}
} else {
if (head->right == NULL) {
head->right = new Node;
head->right->value = value;
head->right->left = NULL;
head->right->right = NULL;
//cout << head->right << " and value =" << head->right->value << endl;
} else {
build_tree(head->right, value);
}
}
}
void signal_handler(int a)
{
cout << "^c was caught" << endl;
interrupt_raised = 1;
}
//main
int main()
{
Node* root = NULL;
signal(SIGINT, signal_handler);
while (interrupt_raised == 0) {
cout << "please enter some value:";
int value;
cin >> value;
if ( root == NULL ) {
root = new Node;
root->value = value;
} else {
build_tree(root, value);
//print_tree(root);
}
}
print_tree(root, 0);
cout << "***************************" << endl;
cout << "Final tree looks like below" << endl;
cout << "***************************" << endl;
display_tree();
return 0;
}