-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.c
More file actions
78 lines (64 loc) · 1.86 KB
/
Copy pathBST.c
File metadata and controls
78 lines (64 loc) · 1.86 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
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* r;
struct node* l;
};
struct node* newNode(int val){
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp->data = val;
temp->r = NULL;
temp->l = NULL;
return temp;
}
struct node* insert(struct node* root, int val){
if(root == NULL)
return newNode(val);
if(root->data > val)
root->l = insert(root->l, val);
else if(root->data < val)
root->r = insert(root->r, val);
return root;
}
struct node* search(struct node* root, int target){
if(root == NULL || root->data == target)
return root;
if(root->data > target)
return search(root->l, target);
else if(root->data < target)
return search(root->r, target);
}
void inorder(struct node* n){
if(n==NULL)
return;
inorder(n->l);
printf("%d\n",n->data);
inorder(n->r);
}
int main(){
int n,i;
struct node* root = NULL;
printf("Enter number of nodes in BST\n");
scanf("%d", &n);
while(n--){
int val;
printf("Enter value to be inserted\n");
scanf("%d", &val);
root = insert(root, val);
}
printf("In-order traversal of BST\n");
inorder(root);
int target;
printf("Enter target element\n");
scanf("%d", &target);
struct node* res;
res = search(root, target);
if(root==NULL)
printf("Tree is empty\n");
else if(root != NULL && res == NULL)
printf("Target element does not occur in BST\n");
else
printf("Target element occurs in BST\n");
return 0;
}