-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST.C
90 lines (90 loc) · 1.83 KB
/
BST.C
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
#include <stdio.h>
#include <stdlib.h>
struct bstnode
{
int data;
struct bstnode *right, *left;
};
struct bstnode *new_node(int data)
{
struct bstnode *nn = (struct bstnode *)malloc(sizeof(struct bstnode));
nn->left = NULL;
nn->right = NULL;
nn->data = data;
return nn;
}
struct bstnode *insert(struct bstnode *root, int data)
{
if (root == NULL)
{
root = new_node(data);
return root;
}
else if (data <= root->data)
{
root->left = insert(root->left, data);
}
else
{
root->right = insert(root->right, data);
}
return root;
}
int search(struct bstnode *root, int data)
{
if (root == NULL)
{
return 0;
}
else if (root->data == data)
{
return 1;
}
else if (data <= root->data)
{
return search(root->left, data);
}
else
{
return search(root->right, data);
}
}
void traverse(struct bstnode *root)
{
if (root != NULL)
{
traverse(root->left);
printf("%d\t", root->data);
traverse(root->right);
}
}
int main()
{
int t, opt;
struct bstnode *root = NULL;
do
{
printf("\nEnter option number: 1. Enter element\t0. Stop adding");
scanf("%d", &opt);
if (opt == 1)
{
printf("\nEnter the element: ");
scanf("%d", &t);
root = insert(root, t);
}
} while (opt != 0);
printf("\nEnter the number you wish to find in the tree: ");
scanf("%d", &t);
search(root, t);
if (t == 1)
{
printf("Found number");
}
else
{
printf("Number not found!");
}
printf("\nThe elements in the tree at given moment is:\n");
traverse(root);
return 0;
}