Repository navigation
Expand file tree
/
Copy pathbinary_search_tree.c
More file actions
129 lines (115 loc) · 2.88 KB
/
Copy pathbinary_search_tree.c
File metadata and controls
129 lines (115 loc) · 2.88 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
117
118
119
120
121
122
123
124
125
126
127
128
129
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *left,*right;
};
typedef struct Node *Nodeptr;
Nodeptr root=NULL,temp;
int n,i,ele,key;
char ch;
Nodeptr getnode(int ele)
{
temp=(Nodeptr)malloc(sizeof(struct Node));
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
return temp;
}
Nodeptr create(Nodeptr ptr,int ele)
{
if(ptr==NULL)
{
temp=getnode(ele);
ptr=temp;
}
else
{
if(ptr->data==ele)
return ptr;
else if(ptr->data<ele)
ptr->right=create(ptr->right,ele);
else if(ptr->data>ele)
ptr->left=create(ptr->left,ele);
}
return ptr;
}
void inorder(Nodeptr temp)
{
if(temp!=NULL)
{
inorder(temp->left);
printf("%d\t",temp->data);
inorder(temp->right);
}
}
void preorder(Nodeptr temp)
{
if(temp!=NULL)
{
printf("%d\t",temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
void postorder(Nodeptr temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf("%d\t",temp->data);
}
}
void search(int key)
{
temp=root;
while(temp!=NULL)
{
if(temp->data==key)
{
printf("The KEY element's search is SUCCESSFUL!\n");
return;
}
else if(temp->data>key)
temp=temp->left;
else
temp=temp->right;
}
printf("The KEY element's search is UNSUCCESSFUL!\n");
}
void main()
{
while(1)
{
printf("\n<-:Binary Search Tree (BST) Operation Menu:->\n1. Create a BST of N Integers\n2. Traverse the BST in InOrder, PreOrder and Post Order\n3. Search the BST for a given KEY element\n4. Exit\nEnter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the number of Nodes:\n");
scanf("%d",&n);
printf("Enter %d Nodes:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&ele);
root=create(root,ele);
}
break;
case 2: printf("\nThe INORDER traversal for given BST is:\n");
inorder(root);
printf("\nThe PREORDER traversal for given BST is:\n");
preorder(root);
printf("\nThe POSTORDER traversal for given BST is:\n");
postorder(root);
printf("\n");
break;
case 3: printf("Enter the KEY value to search\n");
scanf("%d",&key);
search(key);
break;
case 4: exit(0);
default: printf("Enter a Valid Choice.\n");
}
}
}