-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11 min max binary.txt
131 lines (107 loc) · 2.28 KB
/
11 min max binary.txt
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
130
131
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root=NULL;
struct node *getnode(int n);
struct node *insert(struct node *root,int data);
int countNodes(struct node* root);
int height(struct node* root);
int minValue(struct node* node);
int maxValue(struct node* node);
void main()
{
int ch,n,a,k;
printf("Binary Search Tree Operations\n");
while(1)
{
scanf("%d",&ch);
switch(ch)
{
case 1:
scanf("%d",&n);
root=insert(root,n);
break;
case 2:
printf("NUMBER OF NODES IN BST = %d\n", countNodes(root));
break;
case 3:
printf("HEIGHT OF BST IS = %d\n", (height(root)-1));
break;
case 4: printf("MINIMUM VALUE IN BST IS = %d\n", minValue(root));
break;
case 5: printf("MAXIMUM VALUE IN BST IS = %d\n", maxValue(root));
break;
case 6: exit(0);
default: printf("Invalid Choice");
}
}
}
struct node *getnode(int n)
{
struct node *temp=(struct node *)malloc(sizeof(struct node));
temp->data=n;
temp->left=NULL;
temp->right=NULL;
return temp;
}
struct node *insert(struct node *root,int data)
{
if(root==NULL)
{
root=getnode(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 node *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);
}
int countNodes(struct node* root)
{
if (root == NULL)
return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int height(struct node* root)
{
if (root == NULL)
return 0;
else
{
int lDepth = height(root->left);
int rDepth = height(root->right);
if (lDepth > rDepth)
return(lDepth + 1);
else return(rDepth + 1);
}
}
int minValue(struct node* node)
{
struct node* current = node;
while (current->left != NULL)
current = current->left;
return(current->data);
}
int maxValue(struct node* node)
{
struct node* current = node;
while (current->right != NULL)
current = current->right;
return(current->data);
}