TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
tree.cpp
1
#include <iostream>
2
#include <list>
3
using namespace
std;
4
5
struct
node
{
6
int
val;
7
node
*left;
8
node
*right;
9
};
10
11
void
CreateTree(
node
*curr,
node
*n,
int
x,
char
pos) {
12
if
(n != NULL) {
13
char
ch;
14
cout <<
"\nLeft or Right of "
<< n->val <<
" : "
;
15
cin >> ch;
16
if
(ch ==
'l'
)
17
CreateTree(n, n->left, x, ch);
18
else
if
(ch ==
'r'
)
19
CreateTree(n, n->right, x, ch);
20
}
else
{
21
node
*t =
new
node
;
22
t->val = x;
23
t->left = NULL;
24
t->right = NULL;
25
if
(pos ==
'l'
) {
26
curr->left = t;
27
}
else
if
(pos ==
'r'
) {
28
curr->right = t;
29
}
30
}
31
}
32
33
void
BFT(
node
*n) {
34
list<node *> queue;
35
36
queue.push_back(n);
37
38
while
(!queue.empty()) {
39
n = queue.front();
40
cout << n->val <<
" "
;
41
queue.pop_front();
42
43
if
(n->left != NULL)
44
queue.push_back(n->left);
45
if
(n->right != NULL)
46
queue.push_back(n->right);
47
}
48
}
49
50
void
Pre(
node
*n) {
51
if
(n != NULL) {
52
cout << n->val <<
" "
;
53
Pre(n->left);
54
Pre(n->right);
55
}
56
}
57
58
void
In(
node
*n) {
59
if
(n != NULL) {
60
In(n->left);
61
cout << n->val <<
" "
;
62
In(n->right);
63
}
64
}
65
66
void
Post(
node
*n) {
67
if
(n != NULL) {
68
Post(n->left);
69
Post(n->right);
70
cout << n->val <<
" "
;
71
}
72
}
73
74
int
main
() {
75
int
value;
76
int
ch;
77
node
*root =
new
node
;
78
cout <<
"\nEnter the value of root node :"
;
79
cin >> value;
80
root->val = value;
81
root->left = NULL;
82
root->right = NULL;
83
do
{
84
cout <<
"\n1. Insert"
;
85
cout <<
"\n2. Breadth First"
;
86
cout <<
"\n3. Preorder Depth First"
;
87
cout <<
"\n4. Inorder Depth First"
;
88
cout <<
"\n5. Postorder Depth First"
;
89
90
cout <<
"\nEnter Your Choice : "
;
91
cin >> ch;
92
switch
(ch) {
93
case
1:
94
int
x;
95
char
pos;
96
cout <<
"\nEnter the value to be Inserted : "
;
97
cin >> x;
98
cout <<
"\nLeft or Right of Root : "
;
99
cin >> pos;
100
if
(pos ==
'l'
)
101
CreateTree(root, root->left, x, pos);
102
else
if
(pos ==
'r'
)
103
CreateTree(root, root->right, x, pos);
104
break
;
105
case
2:
106
BFT(root);
107
break
;
108
case
3:
109
Pre(root);
110
break
;
111
case
4:
112
In(root);
113
break
;
114
case
5:
115
Post(root);
116
break
;
117
}
118
}
while
(ch != 0);
119
}
node
struct node { int data; int height; struct node *left; struct node *right;} node
for std::queue
Definition
avltree.cpp:13
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
node
Definition
binary_search_tree.cpp:11
data_structures
tree.cpp
Generated by
1.18.0