forked from sanketpatil02/Code-Overflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary search tree program in c++
81 lines (64 loc) · 1.73 KB
/
Binary search tree program in 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
#include<iostream>
//variable to store maximum number of nodes
int complete_node=15;
//Array to store the tree
char tree[]={'\0','D','A','F','E','B','R','T','G','Q','\0','\0','V','\0','J','L'};
int get_right_child(int index)
{
//node is not null
//and the result must lie within the number of nodes for a complete binary
if(tree[index]!='\0'&& ((2*index)+1)<=complete_node)
return(2*index)+1;
//right child doesn't exist
return -1;
}
int get_left_child(int index)
{
//node is not null
//and the result must lie within the number of nodes for a complete binary
if(tree[index]!='\0' && (2*index)<=complete_node)
return 2*index;
//left child doesn't exist
return -1;
}
void preorder(int index)
{
//checking for valid index and null node
if(index>0 && tree[index]!='\0')
{
printf("%c",tree[index]);//visiting root
preorder(get_left_child(index));//visitingleft subtree
preorder(get_right_child(index));//visiting right subtree
}
}
void postorder(int index)
{
//checking for void index and null node
if(index>0 && tree[index]!='\0')
{
postorder(get_left_child(index));//visiting left subtree
postorder(get_right_child(index));//visiting right subtree
printf("%c",tree[index]);//visiting root
}
}
void inorder(int index)
{
//checking for valid index and null node
if(index>0 && tree[index]!='\0')
{
inorder(get_left_child(index));//visiting left subtree
printf("%c",tree[index]);//visiting root
inorder(get_right_child(index));//visiting right subtree
}
}
int main()
{
printf("Preorder:\n");
preorder(1);
printf("\nPostorder:\n");
postorder(1);
printf("\nInorder:\n");
inorder(1);
printf("\n");
return 0;
}