forked from nayyyhaa/C-codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST-insert-delete
64 lines (62 loc) · 1.4 KB
/
BST-insert-delete
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
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
struct node *left,*right;
int item;
}n;
n *newNode(int key)
{
n *temp=(n*)malloc(sizeof(n));
temp->item=key;
temp->left=temp->right=NULL;
return temp;
}
struct node* insert(struct node* node,int key)
{
if(node==NULL) return newNode(key);
if(node->item>key) node->left = insert(node->left,key);
else if(node->item<key) node->right = insert(node->right,key);
return node;
}
void inorder(struct node* node)
{
if(node!=NULL)
{
inorder(node->left);
cout<<node->item<<" ";
inorder(node->right);
}
}
struct node* deleteNode(struct node* node,int key)
{
if(node==NULL) return node;
if(node->item>key) {node->left=deleteNode(node->left,key); return node;}
else if(node->item<key) {node->right=deleteNode(node->right,key); return node;}
if(node->left==NULL)
{
struct node* temp=node->right;
delete node;
return temp;
}
else if(node->right==NULL)
{
struct node* temp=node->left;
delete node;
return temp;
}
else
{
n* succP=node->right;
n* succ=node->right;
while(succ->left!=NULL)
{
succP=succ;
succ=succ->left;
}
succP->left=succ->right;
node->item=succ->item;
delete succ;
return node;
}
}