forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.cpp
More file actions
138 lines (127 loc) · 2.53 KB
/
Tree.cpp
File metadata and controls
138 lines (127 loc) · 2.53 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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <iostream>
#include <list>
using namespace std;
struct node
{
int val;
node *left;
node *right;
};
void CreateTree(node *curr, node *n, int x, char pos)
{
if (n != NULL)
{
char ch;
cout << "\nLeft or Right of " << n->val << " : ";
cin >> ch;
if (ch == 'l')
CreateTree(n, n->left, x, ch);
else if (ch == 'r')
CreateTree(n, n->right, x, ch);
}
else
{
node *t = new node;
t->val = x;
t->left = NULL;
t->right = NULL;
if (pos == 'l')
{
curr->left = t;
}
else if (pos == 'r')
{
curr->right = t;
}
}
}
void BFT(node *n)
{
list<node*> queue;
queue.push_back(n);
while(!queue.empty())
{
n = queue.front();
cout << n->val << " ";
queue.pop_front();
if(n->left != NULL)
queue.push_back(n->left);
if(n->right != NULL)
queue.push_back(n->right);
}
}
void Pre(node *n)
{
if (n != NULL)
{
cout << n->val << " ";
Pre(n->left);
Pre(n->right);
}
}
void In(node *n)
{
if (n != NULL)
{
In(n->left);
cout << n->val << " ";
In(n->right);
}
}
void Post(node *n)
{
if (n != NULL)
{
Post(n->left);
Post(n->right);
cout << n->val << " ";
}
}
int main()
{
int value;
int ch;
node *root = new node;
cout << "\nEnter the value of root node :";
cin >> value;
root->val = value;
root->left = NULL;
root->right = NULL;
do
{
cout << "\n1. Insert";
cout << "\n2. Breadth First";
cout << "\n3. Preorder Depth First";
cout << "\n4. Inorder Depth First";
cout << "\n5. Postorder Depth First";
cout << "\nEnter Your Choice : ";
cin >> ch;
switch (ch)
{
case 1:
int x;
char pos;
cout << "\nEnter the value to be Inserted : ";
cin >> x;
cout << "\nLeft or Right of Root : ";
cin >> pos;
if (pos == 'l')
CreateTree(root, root->left, x, pos);
else if (pos == 'r')
CreateTree(root, root->right, x, pos);
break;
case 2:
BFT(root);
break;
case 3:
Pre(root);
break;
case 4:
In(root);
break;
case 5:
Post(root);
break;
}
} while (ch != 0);
}