forked from UmiUe/IOTBST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.c
51 lines (47 loc) · 904 Bytes
/
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
#include "bst.h"
#include <stdlib.h>
struct node *newNode(int n)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
if(p == NULL){
printf("Error!\n");
exit(-1);
}
p->key = n;
p->left = p->right = NULL;
return p;
}
struct node *insert(struct node *root, int n)
{
if(root == NULL){
return newNode(n);
}
if (root->key > n)
{
root->left = insert(root->left, n);
}
else if (root->key < n)
{
root->right = insert(root->right, n);
}
else
{
return root;
}
}
void inOrder(struct node *root)
{
if(root != NULL){
inOrder(root->left);
printf("%d ", root->key);
inOrder(root->right);
}
}
void preOrder(struct node *root)
{
if(root != NULL){
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}