-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBinary-Trees.c
120 lines (100 loc) · 2.62 KB
/
Binary-Trees.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
110
111
112
113
114
115
116
117
118
119
120
#include<stdio.h>
#include<stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->data = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void insert(struct TreeNode** root, int val) {
if (*root == NULL) {
*root = createNode(val);
return;
}
struct TreeNode* queue[100];
int front = 0;
int rear = 0;
queue[rear++] = *root;
while (front != rear) {
struct TreeNode* current = queue[front++];
if (current->left == NULL) {
current->left = createNode(val);
break;
}
else {
queue[rear++] = current->left;
}
if (current->right == NULL) {
current->right = createNode(val);
break;
}
else {
queue[rear++] = current->right;
}
}
}
// ---------------Traversals-------------------
// 1. Level-Order (top to bottom and left to right)
void levelOrder(struct TreeNode* root) {
if (root == NULL) return;
struct TreeNode* queue[100];
int front = 0;
int rear = 0;
queue[rear++] = root;
while (front != rear) {
struct TreeNode* current = queue[front++];
printf("%d ", current->data);
if (current->left != NULL)
queue[rear++] = current->left;
if (current->right != NULL)
queue[rear++] = current->right;
}
}
// 2. In-Order (Left - Root - Right)
void inorder(struct TreeNode* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
// 3. Pre-Order (Root - Left - Rigth)
void preorder(struct TreeNode* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
// 4. Post-Order (Left - Right - Root)
void postorder(struct TreeNode* root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
// -------------------------------------------
int main() {
struct TreeNode* root = NULL;
int n;
printf("n = ");
scanf("%d", &n);
while (n--) {
int val;
printf(">>>> ");
scanf("%d", &val);
insert(&root, val);
}
printf("\nLevel order: ");
levelOrder(root);
printf("\nInorder: ");
inorder(root);
printf("\nPreorder: ");
preorder(root);
printf("\nPostorder: ");
postorder(root);
}