-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search Tree - Print Level Order
100 lines (87 loc) · 2.09 KB
/
Binary Search Tree - Print Level Order
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
Implement a C program to print the nodes in a BST in level order.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct tnode
{
int data;
struct tnode * leftc;
struct tnode * rightc;
};
void insert(struct tnode **, int num);
void inorder(struct tnode *);
void printLevelOrder(struct tnode* root);
void printGivenLevel(struct tnode* root, int level);
int height(struct tnode* node);
int main()
{
struct tnode * root=NULL;
char ch[5];
int num;
do {
printf("Enter the element to be inserted in the tree\n");
scanf("%d",&num);
insert(&root, num);
printf("Do you want to insert another element?\n");
scanf("%s",ch);
}while(strcmp(ch,"yes")==0);
printf("Inorder Traversal : The elements in the tree are");
inorder(root);
printf("\n");
printf("The elements in the tree in level order are");
printLevelOrder(root);
printf("\n");
return 0;
}
void insert(struct tnode ** s, int num) {
if((*s) == NULL) {
(*s) = (struct tnode *) malloc( sizeof (struct tnode));
(*s)->data = num;
(*s)->leftc = NULL;
(*s)->rightc = NULL;
}
else {
if(num < (*s)->data)
insert(&( (*s)->leftc ), num);
else
insert(&( (*s)->rightc ), num);
}
}
void inorder(struct tnode * s) {
if(s != NULL) {
inorder(s->leftc);
printf(" %d",s->data);
inorder(s->rightc);
}
}
/* Function to print level order traversal a tree*/
void printLevelOrder(struct tnode* root) {
int h = height(root);
int i;
for(i=1; i<=h; i++)
printGivenLevel(root, i);
}
/* Print nodes at a given level */
void printGivenLevel(struct tnode* root, int level) {
if(root == NULL)
return ;
if(level == 1)
printf(" %d",root->data);
else if(level >1){
printGivenLevel(root->leftc,level-1);
printGivenLevel(root->rightc,level-1);
}
}
int height(struct tnode* node) {
if (node==NULL)
return 0;
else {
/* compute the height of each subtree */
int lheight = height(node->leftc);
int rheight = height(node->rightc);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}