-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Tree Operation.cpp
116 lines (104 loc) · 2.18 KB
/
Binary Search Tree Operation.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<stdlib.h>
using namespace std;
typedef struct node
{
struct node* left;
int payload;
struct node* right;
}Node;
Node* root = NULL;
Node* create();
void Insert(Node*, Node* = root);
void Traversal(Node* = root);
void DeleteWithoutLeftChild(Node* = root);
void DeleteWithoutRightChild(Node* = root);
void DeleteWithChild(Node* = root, char = 'r');
void main()
{
for (int i = 0; i < 7; i++)
Insert(create());
cout << "Display the elements: \n";
Traversal();
DeleteWithChild();
cout << "Display the elements: \n";
Traversal();
system("pause");
}
void Insert(Node* ptr, Node* temp)
{
if (temp == NULL)
root = ptr;
else if (temp->payload < ptr->payload)
{
if (temp->right == NULL)
temp->right = ptr;
else
Insert(ptr,temp->right);
}
else if (temp->payload > ptr->payload)
{
if (temp->left == NULL)
temp->left = ptr;
else
Insert(ptr, temp->left);
}
}
void Traversal(Node* temp)
{
if (temp)
{
Traversal(temp->left);
cout << temp->payload << " ";
Traversal(temp->right);
}
}
Node* create()
{
Node* ptr = (Node*)calloc(1, sizeof(Node));
cout << "Enter Payload: ";
cin >> ptr->payload;
return ptr;
}
void DeleteWithoutLeftChild(Node* parent)
{
Node* temp = parent->left;
if (temp->left != NULL)
DeleteWithoutLeftChild(parent->left);
else
{
parent->left = temp->right;
cout <<endl<< "Node is : " << temp->payload << endl;
free(temp);
return;
}
}
void DeleteWithoutRightChild(Node* parent)
{
Node* temp = parent->right;
if (temp->right != NULL)
DeleteWithoutRightChild(parent->right);
else
{
parent->right = temp->left;
cout << endl<< "Node is : " << temp->payload<< endl;
free(temp);
}
}
void DeleteWithChild(Node* parent1, char ch)
{
Node* parent;
if (ch = 'r')
parent = parent1->right;
else
parent = parent1->left;
if (!parent->left->left && !parent->left->right && !parent->right->left && !parent->right->right)
{
parent1->right = parent->right;
parent->right->left = parent->left;
cout << "\nNode is : " << parent->payload << endl;
free(parent);
}
else
DeleteWithChild(parent);
}