forked from thisisshub/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.c
104 lines (91 loc) · 1.9 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//implementation of Binary Search Tree in C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int max(int a, int b);
typedef struct BST
{
int data;
struct BST *left;
struct BST *right;
} BST;
BST *createNode(int x)
{
BST *temp = malloc(sizeof *temp);
temp->data = x;
temp->left = NULL;
temp->right = NULL;
return temp;
}
BST *insertNode(BST *root, int x)
{
if (root == NULL)
return createNode(x);
if (x < root->data)
root->left = insertNode(root->left, x);
else if (x > root->data)
root->right = insertNode(root->right, x);
return root;
}
void inorder(BST *root)
{
if (root == NULL)
return;
inorder(root->left);
printf("%d ->", root->data);
inorder(root->right);
}
bool searchBST(BST *root, int x)
{
if (root == NULL)
return false;
if (root->data == x)
return true;
else if (x < root->data)
return searchBST(root->left, x);
else
return searchBST(root->right, x);
}
int heightBST(BST *root)
{
if (root == NULL)
return 0;
else
return max(heightBST(root->left), heightBST(root->right)) + 1;
}
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
int maxElement(BST *root)
{
if (root == NULL)
{
printf("The tree is empty\n");
return -1;
}
else if (root->right == NULL)
return root->data;
return maxElement(root->right);
}
int main(int argc, char const *argv[])
{
/* code */
BST *root = NULL;
root = insertNode(root, 8);
insertNode(root, 3);
insertNode(root, 1);
insertNode(root, 6);
insertNode(root, 7);
insertNode(root, 10);
insertNode(root, 14);
insertNode(root, 4);
inorder(root);
int max = maxElement(root);
printf("height of tree is %d\n", heightBST(root));
printf("\nThe maximum element is %d\n", max);
return 0;
}