-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.c
109 lines (94 loc) · 2.06 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
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
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
struct node *left;
struct node *right;
int data;
}Node;
Node *createNode(){
Node *root = malloc(sizeof(Node));
root->left = root->right = NULL;
return root;
}
void add(Node *root, Node *p){
if(root->data > p->data){
if(root->left == NULL)
root->left = p;
else
add(root->left, p);
}
else if(root->data < p->data){
if(root->right == NULL)
root->right = p;
else
add(root->right, p);
}
}
Node *addNode(Node *root,int data){
Node *new = malloc(sizeof(Node));
new->left = new->right = NULL;
new->data = data;
if(root == NULL)
{
root = (Node *) add;
return root;
}
else
add(root,new);
return NULL;
}
void preOrder(Node *root){
if(root != NULL){
printf("%d ",root->data);
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(Node *root){
if(root != NULL){
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}
void postOrder(Node *root){
if(root != NULL){
inOrder(root->left);
inOrder(root->right);
printf("%d ", root->data);
}
}
int main(void)
{
/* CREATE THE TREE*/
Node *root = createNode();
root->data = 14;
addNode(root,4);
addNode(root,15);
addNode(root,3);
addNode(root,9);
addNode(root,7);
addNode(root,9);
addNode(root,5);
addNode(root,4);
addNode(root,5);
addNode(root,14);
addNode(root,18);
addNode(root,16);
addNode(root,20);
addNode(root,17);
/* PRINT THE TREE*/
printf("PREORDER\n");
printf("===================\n");
preOrder(root);
printf("\n===================");
printf("\nPOSTORDER\n");
printf("===================\n");
postOrder(root);
printf("\n===================");
printf("\nINORDER\n");
printf("===================\n");
inOrder(root);
printf("\n===================\n");
return 0;
}