-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.cpp
128 lines (105 loc) · 2.03 KB
/
bst.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
// C++ program to insert a node in AVL tree
#include <iostream>
#include <climits>
#include <cstdlib>
using namespace std;
struct node
{
int key;
struct node *left, *right;
};
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
cout<<root->key<<" ";
inorder(root->right);
}
}
void preorder(struct node *root)
{
if (root != NULL)
{
cout<<root->key<<" ";
preorder(root->left);
preorder(root->right);
}
}
struct node* insert(struct node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
struct node* findmin(struct node* root)
{
while(root->left!=NULL)
{
root=root->left;
}
return root;
}
struct node* del(struct node *root,int key)
{
if(root==NULL)
return root;
if(key<root->key)
root->left=del(root->left,key);
else if(key>root->key)
root->right=del(root->right,key);
else
{
if(root->left==NULL)
{
struct node* temp=root->right;
free(root);
return temp;
}
else if(root->right==NULL)
{struct node* temp=root->left;
free(root);
return temp;
}
else
{
struct node* temp=findmin(root->right);
root->key=temp->key;
root->right=del(root->right,temp->key);
}
}
}
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
// insert(root,10);
insert(root, 60);
insert(root, 80);
del(root,50);
// print inoder traversal of the BST
inorder(root);
cout<<"\n";
preorder(root);
return 0;
}