-
Notifications
You must be signed in to change notification settings - Fork 1
/
height_tree_iteration.c
153 lines (136 loc) · 2.12 KB
/
height_tree_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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.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;
}
struct queue
{
struct node* queues;
struct queue* link;
}*front=NULL,*rear=NULL;
struct queue* newNode1(struct node* root)
{
struct queue *newnode;
newnode=(struct queue *)malloc(sizeof(struct queue));
newnode->queues=root;
newnode->link=NULL;
return newnode;
}
void enqueue(struct node* x)
{
struct queue *temp;
temp=newNode1(x);
if (rear==NULL){
front=rear=temp;
front->link=NULL;
rear->link=NULL;
}
else
{
rear->link=temp;
rear=temp;
}
}
void dequeue()
{
struct node *temp;
temp=front->queues;
if (front==NULL)
{
printf("Queue is empty\n");
front=rear=NULL;
}
else
{
if(front==rear){
front=NULL;
rear=NULL;
}
else
front=front->link;
free(temp);
}
}
int sizeofqueue(){
struct queue* back=front;
int count=0;
while(back!=NULL){
count++;
back=back->link;
}
return count;
}
int height(struct node* root){
int h=0;
enqueue(root);
while(1){
int count=sizeofqueue();
if (count==0)
{
return h;
}
else{
h++;
}
while(count>0){
struct node* cur;
cur=front->queues;
dequeue();
if (cur->right!=NULL)
{
enqueue(cur->right);
}
if (cur->left!=NULL)
{
enqueue(cur->left);
}
count--;
}
}
return h;
}
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=height(root);
printf("%d\n",h );
return 0;
}