-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary tree traversal.c
93 lines (84 loc) · 2.73 KB
/
binary tree traversal.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
#include <stdio.h>
#include <stdlib.h>
struct tnode {
int data;
struct tnode *left, *right;
};
struct tnode *root = NULL;
/* creating node of the tree and fill the given data */
struct tnode * createNode(int data) {
struct tnode *newNode;
newNode = (struct tnode *) malloc(sizeof(struct tnode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return (newNode);
}
/* inserting a new node into the tree */
void insertion(struct tnode **node, int data) {
if (!*node) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
}
}
/* post order tree traversal */
void postOrder(struct tnode *node) {
if (node) {
postOrder(node->left);
postOrder(node->right);
printf("%d ", node->data);
}
return;
}
/* pre order tree traversal */
void preOrder(struct tnode *node) {
if (node) {
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
return;
}
/* inorder tree traversal */
void inOrder(struct tnode *node) {
if (node) {
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
return;
}
int main() {
int data, ch;
while (1) {
printf("\n1. Insertion\n2. Pre-order\n");
printf("3. Post-order\n4. In-order\n");
printf("5. Exit\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter ur data:");
scanf("%d", &data);
insertion(&root, data);
break;
case 2:
preOrder(root);
break;
case 3:
postOrder(root);
break;
case 4:
inOrder(root);
break;
case 5:
exit(0);
default:
printf("U've entered wrong opetion\n");
break;
}
}
return 0;
}