-
Notifications
You must be signed in to change notification settings - Fork 2
/
BinaryTreeCreateTraversal.c
85 lines (74 loc) · 1.94 KB
/
BinaryTreeCreateTraversal.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
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node{
struct node *left;
int data;
struct node *right;
};
struct node *root = NULL;
struct node *tree = NULL;
struct node *createNode(int data){
if(data == -1){
return NULL;
}
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = data;
ptr->right = NULL;
ptr->left = NULL;
return ptr;
}
void createTree(struct node *root){
int data;
if(root == NULL){
printf("\nEnter the value of the element(root):\t");
scanf("%d",&data);
root = createNode(data);
tree = root;
}
printf("\nThe value of the root element is %d",root->data);
printf("\nEnter the value of the left child.Enter -1 to put NULL:\t");
scanf("%d",&data);
root->left = createNode(data);
printf("\nEnter the value of the right child. Enter -1 to put NULL:\t");
scanf("%d",&data);
root->right = createNode(data);
if(root->left != NULL){
createTree(root->left);
}
if(root->right != NULL){
createTree(root->right);
}
}
void inOrderTraversal(struct node *root){
if(root != NULL){
inOrderTraversal(root->left);
printf("%d ",root->data);
inOrderTraversal(root->right);
}
}
void PreOrderTraversal(struct node *root){
if(root != NULL){
printf("%d ",root->data);
PreOrderTraversal(root->left);
PreOrderTraversal(root->right);
}
}
void postOrderTraversal(struct node *root){
if(root != NULL){
postOrderTraversal(root->left);
postOrderTraversal(root->right);
printf("%d ",root->data);
}
}
void main(){
printf("\nCreating the tree...");
createTree(tree);
printf("\nTree created successfully");
printf("\nInOrderTraversal:\t");
inOrderTraversal(tree);
printf("\nPreOrderTraversal:\t");
preOrderTraversal(tree);
printf("\nPostOrderTraversal:\t");
postOrderTraversal(tree);
}