-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarytree.c
79 lines (74 loc) · 1.81 KB
/
binarytree.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
//
// Created by Ti Kyi Khant on 3/16/2023.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct treenode{
struct treenode * leftptr;
int data;
struct treenode * rightptr;
};
typedef struct treenode treeNode;
typedef treeNode * treeptr;
int insertNode(treeptr * base, int value);
void inOrder(treeptr baseptr);
void preOrder(treeptr baseptr);
void postOrder(treeptr baseptr);
int main() {
treeptr root = NULL;
srand(time(NULL));
puts("The numbers generated:\n");
for(int i = 0; i < 10; i++){
int item = rand() % 15;
insertNode(&root,item);
printf(" %d ",item);
}
printf("InOrder going:\n");
preOrder(root);
return 0;
}
int insertNode(treeptr * base, int value){
if(*base == NULL){
*base = malloc(sizeof(treeNode));
if(*base != NULL){
(*base)->data = value;
(*base)->leftptr = NULL;
(*base)->rightptr = NULL;
}else{
printf("No value are inserted , insufficient memory\n");
}
}
else{
if(value < (*base)->data){
insertNode(&((*base)->leftptr), value);
}
else if(value > (*base)->data){
insertNode(&((*base)->rightptr),value);
}
else{
printf("No duplicate values allowed;\n");
}
}
}
void inOrder(treeptr baseptr){
if(baseptr != NULL){
inOrder(baseptr->leftptr);
printf(" %d " ,baseptr->data);
inOrder(baseptr->rightptr);
}
}
void preOrder(treeptr baseptr){
if(baseptr != NULL){
printf(" %d ",baseptr->data);
preOrder(baseptr->leftptr);
preOrder(baseptr->rightptr);
}
}
void postOrder(treeptr baseptr){
if(baseptr != NULL){
postOrder(baseptr->leftptr);
postOrder(baseptr->rightptr);
printf(" %d ",baseptr->data);
}
}