forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Preordertraversal.c
123 lines (113 loc) · 2.46 KB
/
Preordertraversal.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
121
122
123
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct BST{
int data;
struct BST *left;
struct BST *right;
};
struct BST* create();
void insert(struct BST*, struct BST*);
void preorderRecursive(struct BST*);
void preorderIterative(struct BST*);
int main(){
char ch;
struct BST *root=NULL, *temp;
do{
temp=create();
if(root==NULL){
root=temp;
printf("Element inserted successfully! \n");
}
else{
insert(root,temp);
printf("Element inserted successfully! \n");
}
printf("Do you want to enter more data? (y/n) ");
getchar();
scanf("%c", &ch);
}while(ch=='y' || ch== 'Y');
printf("\nPreorder traversal using recursion\n");
preorderRecursive(root);
printf("\nPreorder traversal using iteration\n");
preorderIterative(root);
getch();
return 0;
}
struct BST *create(){
struct BST *temp;
printf("Enter data: ");
temp=(struct BST*)malloc(sizeof(struct BST*));
scanf("%d", &temp->data);
temp->left=NULL;
temp->right=NULL;
return temp;
}
void insert(struct BST *root, struct BST *temp){
if(temp->data<root->data){
if(root->left==NULL){
root->left=temp;
}
else{
root=root->left;
insert(root, temp);
}
}
else if(temp->data>root->data){
if(root->right==NULL){
root->right=temp;
}
else{
root=root->right;
insert(root, temp);
}
}
}
void preorderRecursive(struct BST *root){
if(root!=NULL){
printf("%d ", root->data);
preorderIterative(root->left);
preorderIterative(root->right);
}
}
void preorderIterative(struct BST* root)
{
while(root){
if(root->left!=NULL){
struct BST* node = root->left;
while(node->right && node->right != root){
node=node->right;
}
if(node->right==root){
node->right=NULL;
root=root->right;
}
else{
printf("%d ", root->data);
node->right=root;
root=root->left;
}
}
else{
printf("%d ", root->data);
root=root->right;
}
}
}
// Sample Output
// Enter data: 5
// Element inserted successfully!
// Do you want to enter more data? (y/n) y
// Enter data: 3
// Element inserted successfully!
// Do you want to enter more data? (y/n) y
// Enter data: 8
// Element inserted successfully!
// Do you want to enter more data? (y/n) y
// Enter data: 7
// Element inserted successfully!
// Do you want to enter more data? (y/n) n
// Preorder traversal using recursion
// 5 3 8 7
// Preorder traversal using iteration
// 5 3 8 7