-
Notifications
You must be signed in to change notification settings - Fork 1
/
level_order_travesal_iteration.c
80 lines (69 loc) · 1.46 KB
/
level_order_travesal_iteration.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
#include "stdio.h"
#include "stdlib.h"
struct node
{
int data;
struct node* right;
struct node* left;
};
struct node* get_newnode(int data){
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->right=newnode->left=NULL;
return newnode;
}
struct node* insert(struct node* root, int data){
if (root==NULL)
{
root=get_newnode(data);
}
else if(root->data>=data){
root->left=insert(root->left,data);
}
else {
root->right = insert(root->right,data);
}
return root;
}
int max(int a,int b){
if (a>b)
{
return a;
}
return b;
}
int find_height(struct node* root){
if (root==NULL)
{
return 0;
}
return max(find_height(root->left), find_height(root->right))+1;
}
void level_order(struct node* root, int level)
{
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
level_order(root->left, level-1);
level_order(root->right, level-1);
}
}
int main(int argc, char const *argv[])
{
struct node* root=(struct node*)malloc(sizeof(struct node));
root=NULL;
root=insert(root,50);
root=insert(root,59);
root=insert(root,75);
root=insert(root,100);
root=insert(root,3);
root=insert(root,99);
int h = find_height(root);
int i;
for (i=1; i<=h; i++)
level_order(root, i);
return 0;
}