-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_traversal.c
121 lines (95 loc) · 1.99 KB
/
binary_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
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
// C program to demonstrate binary search tree with Traversal.
/* Created by Jithin K c */
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int key;
struct node *left, *right;
};
// function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// function to insert a new node with given key in BST
struct node* insert(struct node* node, int key)
{
// If the tree is empty, return a new node
if (node == NULL) return newNode(key);
// Otherwise, recur down the tree
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
// return the (unchanged) node pointer
return node;
}
// function to do inorder traversal of BST
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%c ", root->key);
inorder(root->right);
}
}
// function to do preorder traversal of BST
void preorder(struct node *root)
{
if (root != NULL)
{
printf("%c ", root->key);
preorder(root->left);
preorder(root->right);
}
}
// function to do postorder traversal of BST
void postorder(struct node *root)
{
if (root != NULL)
{
postorder(root->left);
postorder(root->right);
printf("%c ", root->key);
}
}
// Main Function
int main()
{
struct node *root = NULL;
int m;
printf("Enter the max value and elements:");
scanf("%d", &m);
for(int i=0;i<m;i++)
{
char ap;
//printf("enter the element:");
scanf("%c", &ap);
int n = ap;
// printf("%d\n",n);
if(i==0)
{
root=insert(root,n);
}
else
{
insert(root,n);
}
}
// print inoder traversal of the BST
printf("\n inorder traversal: \n");
inorder(root);
printf("\n preorder traversal: \n");
// print preoder traversal of the BST
preorder(root);
// print postoder traversal of the BST
printf("\n postorder traversal:\n");
postorder(root);
return 0;
}