-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree LL
127 lines (127 loc) · 2.13 KB
/
BinaryTree LL
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
#include <stdio.h>
#include <stdlib.h>
struct node *minvalues(struct node *node);
struct node *delnode(struct node *tree,int data);
struct node *insert(struct node *tree,int data);
void inorder(struct node *tree);
void preorder(struct node *tree);
void postorder(struct node *tree);
struct node{
int data;
struct node *rc,*lc;
}*root,*tree,*temp;
void main()
{
int n,ch,a;
do{
printf("\t\tMENU\n1: Insert\n2: Delete\n3: Inorder\n4: Postorder\n5: Preorder\n");
printf("Enter the option:");
scanf("%d",&ch);
switch(ch){
case 1:printf("Enter the element:");
scanf("%d",&n);
root=insert(root,n);
break;
case 2:printf("Enter the element:");
scanf("%d",&n);
root=delnode(root,n);
break;
case 3:printf("Tree :");
inorder(root);
break;
case 4:printf("Tree :");
postorder(root);
break;
case 5:printf("Tree :");
preorder(root);
break;
}
printf("\nExit? (1/0) :");
scanf("%d",&a);
}while(a==1);
}
struct node *minvalues(struct node *node)
{
struct node *c=node;
while(c->lc!=NULL)
{
c=c->lc;
return c;
}
}
struct node *delnode(struct node *tree,int data)
{
if(tree==NULL)
return tree;
else if(data < tree->data)
tree->lc=delnode(tree->lc,data);
else if(data > tree->data)
tree->rc=delnode(tree->rc,data);
else
{
if(tree->lc==NULL)
{
struct node *temp=tree->rc;
free(tree);
return temp;
}
else if(tree->rc==NULL)
{
struct node *temp=tree->lc;
free(tree);
return temp;
}
struct node *temp=minvalues(tree->rc);
tree->data=temp->data;
tree->rc=delnode(tree->rc,tree->data);
}
return tree;
}
struct node *insert(struct node *tree,int data)
{
if(tree==NULL)
{
tree=(struct node *)malloc(sizeof(struct node));
tree->data=data;
tree->rc=NULL;
tree->lc=NULL;
return tree;
}
else if(tree->data > data)
{
tree->lc=insert(tree->lc,data);
return tree;
}
else if(tree->data < data)
{
tree->rc=insert(tree->rc,data);
return tree;
}
}
void inorder(struct node *tree)
{
if(tree!=NULL)
{
inorder(tree->lc);
printf("%d\t",tree->data);
inorder(tree->rc);
}
}
void preorder(struct node *tree)
{
if(tree!=NULL)
{
printf("%d\t",tree->data);
preorder(tree->lc);
preorder(tree->rc);
}
}
void postorder(struct node *tree)
{
if(tree!=NULL)
{
postorder(tree->lc);
postorder(tree->rc);
printf("%d\t",tree->data);
}
}