-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimplement of binary search tree .c
92 lines (70 loc) · 1.48 KB
/
implement of binary search tree .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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct node{
int data;
struct node* left;
struct node* right;
};
typedef struct node* Node;
Node createNode(int data){
Node newNode = (Node) malloc (sizeof(Node));
newNode ->data = data;
newNode ->left = NULL;
newNode ->right = NULL;
return newNode;
}
Node add(Node root, int data){
Node newNode = createNode(data);
if(root == NULL){
return newNode;
}
if(root->data > data){
root->left = add(root->left, data);
}else if(root->data < data){
root->right = add(root->right, data);
}
return root;
}
Node min_Node(Node root){
if(root == NULL)
return NULL;
if(root->left != NULL)
return min_Node(root->left);
return root;
}
Node max_Node(Node root){
if(root == NULL)
return NULL;
if(root->right != NULL)
return max_Node(root->right);
return root;
}
int min(Node root){
return (min_Node(root))->data;
}
int max(Node root){
return (max_Node(root))->data;
}
void inorder(Node root){
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main(void) {
Node root;
srand(time(NULL));
for(int i = 0; i < 10 ; i++){
if(i == 0)
root = createNode(rand()%10);
root = add(root,rand()%10);
}
printf("show binary sreach tree sorted \n");
inorder(root);
printf("\nmin = %d",min(root));
printf("\nmax = %d",max(root));
printf("\nroot = %d",root->data);
return 0;
}