-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path50-binarysearchtree.cpp
More file actions
116 lines (110 loc) · 2.33 KB
/
Copy path50-binarysearchtree.cpp
File metadata and controls
116 lines (110 loc) · 2.33 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
//insert a node at specific direction like RRLLR direction
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string.h>
using namespace std;
struct node
{
int info;
struct node *llink;
struct node *rlink;
};
class bst
{
public:
node* insert(int item,node *root)
{
node *temp=new node;
node *cur=new node;
node *prev=new node;
temp->info=item;
temp->rlink=temp->llink=NULL;
if(root==NULL)
return temp;
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
cur=item<cur->info?cur->llink:cur->rlink;
}
if(item<prev->info)
prev->llink=temp;
else
prev->rlink=temp;
return root;
}
void preorder(node *root)
{
if(root!=NULL)
{
cout<<root->info<<endl;
preorder(root->llink);
preorder(root->rlink);
}
}
node* deleteitem(int item,node *root)
{
node *parent=new node;
node *cur=new node;
node *suc=new node;
node *q=new node;
if(root==NULL)
{
cout<<"empty";
return root;
}
parent=NULL;
cur=root;
while(cur!=NULL&&item!=cur->info)
{
parent=cur;
cur=item<cur->info?cur->llink:cur->rlink;
}
if(cur==NULL)
{
cout<<"item not found";
return root;
}
if(cur->llink==NULL)
q=cur->rlink;
else if(cur->rlink==NULL)
q=cur->llink;
else
{
suc=cur->rlink;
while(suc->llink!=NULL)
suc=suc->llink;
suc->llink=cur->llink;
q=cur->rlink;
}
if(cur==parent->llink)
parent->llink=q;
else
parent->rlink=q;
delete cur;
return root;
}
};
int main()
{
bst obj;
node *root=NULL;
while(true)
{
int item;
cout<<"enter item"<<endl;
cin>>item;
if(item<0)
break;
root=obj.insert(item,root);
}
obj.preorder(root);
int item;
cout<<"enter item to delete";
cin>>item;
root=obj.deleteitem(item,root);
cout<<"After deletion function:\n";
obj.preorder(root);
}