-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.c
79 lines (78 loc) · 1.49 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
#include <stdio.h>
#include <stdlib.h>
typedef struct node Node;
struct node
{
Node* lchild;
int data;
Node* rchild;
};
void bst_insert(Node **root, int value);
Node* bst_search(Node* root, int value);
void inorder(Node *temp);
int main(int argc, char* argv[])
{
Node* root=NULL;
for(int i = 0; i<10; i++)
{
bst_insert(&root,i);
}
inorder(root);
return 0;
}
Node* bst_search(Node* root, int value)
{
while(root)
{
if (root->data == value)
{
return root;
}
else if (root->data > value)
{
root=root->lchild;
}
else{
root=root->rchild;
}
}
return NULL;
}
void inorder(Node *temp)
{
if (temp)
{
inorder(temp->lchild);
printf("%d ",temp->data);
inorder(temp->rchild);
}
}
void bst_insert(Node **root, int value)
{
Node *temp,*mover=*root,*prev;
if (*root == NULL)
{
temp = (Node*)malloc(sizeof(Node));
temp->data=value;
temp->lchild=temp->rchild=NULL;
*root = temp;
return;
}
while (mover)
{
prev=mover;
if (mover->data > value)
{
mover=mover->lchild;
}
else if (mover->data < value)
{
mover=mover->rchild;
}
}
temp = (Node*)malloc(sizeof(Node));
temp->data=value;
temp->lchild=temp->rchild=NULL;
if (prev->data > value) prev->lchild=temp;
else prev->rchild=temp;
}