-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbinary_tree.cpp
138 lines (126 loc) · 3.05 KB
/
binary_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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Binary Tree in C++
#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
// New node creation
struct node *newNode(int data)
{
struct node *node = (struct node *)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void traversePreOrder(struct node *temp);
void traverseInOrder(struct node *temp);
void traversePostOrder(struct node *temp);
int main()
{
struct node *root = NULL;
// menu driven
int choice, data;
char ch = 'y';
while (ch == 'y' || ch == 'Y')
{
loop:
cout << "1. Insert" << endl
<< "2. Preorder Traversal" << endl
<< "3. Inorder Traversal" << endl
<< "4. Postorder Traversal" << endl
<< "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the data: ";
cin >> data;
if (root == NULL)
{
root = newNode(data);
}
else
{
struct node *temp = root;
struct node *parent = NULL;
while (temp != NULL)
{
parent = temp;
if (data < temp->data)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
if (data < parent->data)
{
parent->left = newNode(data);
}
else
{
parent->right = newNode(data);
}
}
break;
case 2:
cout << "\nPreorder Traversal: ";
traversePreOrder(root);
cout << endl;
break;
case 3:
cout << "\n\nInorder Traversal: ";
traverseInOrder(root);
cout << endl;
break;
case 4:
cout << "\n\nPostorder Traversal: ";
traversePostOrder(root);
cout << endl;
break;
default:
cout << "\n\nInvalid choice" << endl;
goto loop;
}
cout << "\nDo you want to continue? (y/n): ";
cin >> ch;
}
return 0;
}
// Traverse Preorder
void traversePreOrder(struct node *temp)
{
if (temp != NULL)
{
cout << temp->data << "->";
traversePreOrder(temp->left);
traversePreOrder(temp->right);
}
}
// Traverse Inorder
void traverseInOrder(struct node *temp)
{
if (temp != NULL)
{
traverseInOrder(temp->left);
cout << temp->data << "->";
traverseInOrder(temp->right);
}
}
// Traverse Postorder
void traversePostOrder(struct node *temp)
{
if (temp != NULL)
{
traversePostOrder(temp->left);
traversePostOrder(temp->right);
cout << temp->data << "->";
}
}