-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path61.c
More file actions
73 lines (58 loc) · 1.4 KB
/
61.c
File metadata and controls
73 lines (58 loc) · 1.4 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
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
// Insert in BST
struct node* insert(struct node *root, int x) {
if(root == NULL) {
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = x;
newnode->left = newnode->right = NULL;
return newnode;
}
if(x < root->data)
root->left = insert(root->left, x);
else
root->right = insert(root->right, x);
return root;
}
// Inorder Traversal (Sorted output)
void inorder(struct node *root) {
if(root == NULL)
return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
// Search in BST
int search(struct node *root, int key) {
if(root == NULL)
return 0;
if(root->data == key)
return 1;
else if(key < root->data)
return search(root->left, key);
else
return search(root->right, key);
}
int main() {
struct node *root = NULL;
int n, x, i, key;
printf("Enter number of nodes: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
scanf("%d", &x);
root = insert(root, x);
}
printf("Inorder Traversal: ");
inorder(root);
printf("\nEnter element to search: ");
scanf("%d", &key);
if(search(root, key))
printf("Element Found");
else
printf("Element Not Found");
return 0;
}