Skip to content

Commit 84c6826

Browse files
committed
📚 chore: Update display tree function
1 parent ad07aab commit 84c6826

File tree

1 file changed

+99
-6
lines changed

1 file changed

+99
-6
lines changed

tree_traversal.c

Lines changed: 99 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
#include<stdio.h>
22
#include<stdlib.h>
3-
3+
//8+8/2*3+8/2=23
44
//queue functions
5-
/*
6-
1
7-
2 3
8-
4 5 6 7
5+
/* L I
6+
1 12 N
7+
2 3 6 11
8+
4 5 6 7 3 5
9+
8 9 1 1 1 1 1 1 1 3
10+
11+
1
12+
1 1
13+
1 1 1 1
14+
1 1 1 1 1 1 1 1
15+
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
916
*/
1017
struct node
1118
{
@@ -20,6 +27,12 @@ struct node* new_qNode(struct t_node* x)
2027
temp->data=x;
2128
return temp;
2229
}
30+
int q_size(struct node* head)
31+
{
32+
if(!head)
33+
return 0;
34+
return 1+q_size(head->next);
35+
}
2336
//queue functions
2437

2538

@@ -67,6 +80,81 @@ void Postorder(struct t_node* root)
6780
printf("%d ",root->data);
6881
}
6982

83+
int height(struct t_node* root)
84+
{
85+
if(!root)
86+
{
87+
return 0;
88+
}
89+
int l,r;
90+
l=height(root->left);
91+
r=height(root->right);
92+
if(l>r)
93+
{
94+
return l+1;
95+
}
96+
else
97+
{
98+
return r+1;
99+
}
100+
}
101+
void d_spaces(int space)
102+
{
103+
for(int i=0;i<space;++i)
104+
{
105+
printf(" ");
106+
}
107+
}
108+
109+
void display(struct t_node* root)
110+
{
111+
struct node* head=new_qNode(root);
112+
struct node* tail=head;
113+
int h=(1<<height(root)-1);
114+
int internal;
115+
int x=1;
116+
int spaces=h/2+(h/4)*3+(h/4);
117+
if(spaces==1)
118+
spaces=3;
119+
while(x<=h)
120+
{
121+
d_spaces(spaces);
122+
internal=spaces*2-1;
123+
if(x==h)
124+
internal=3;
125+
int c=0;
126+
for(int i=0;i<x;++i)
127+
{
128+
struct t_node* temp=head->data;
129+
printf("%d",temp->data);
130+
++c;
131+
if(x!=h)
132+
d_spaces(internal);
133+
else
134+
{
135+
if(c&1)
136+
d_spaces(internal);
137+
else
138+
printf(" ");
139+
}
140+
if(temp->left)
141+
{
142+
tail->next=new_qNode(temp->left);
143+
tail=tail->next;
144+
}
145+
if(temp->right)
146+
{
147+
tail->next=new_qNode(temp->right);
148+
tail=tail->next;
149+
}
150+
head=head->next;
151+
}
152+
printf("\n");
153+
x*=2;
154+
spaces/=2;
155+
}
156+
}
157+
70158

71159
/*
72160
1. 1
@@ -120,7 +208,7 @@ int main()
120208
int c=1,choice;
121209
while(c)
122210
{
123-
printf("1.In-order Traversal\n2.Pre-order Traversal\n3.Post-order traversal\n4.Exit\nEnter your choice: ");
211+
printf("1.In-order Traversal\n2.Pre-order Traversal\n3.Post-order traversal\n4.Display\n5.Exit\nEnter your choice: ");
124212
scanf("%d",&choice);
125213
switch(choice)
126214
{
@@ -143,6 +231,11 @@ int main()
143231
break;
144232
}
145233
case 4:
234+
{
235+
display(root);
236+
break;
237+
}
238+
case 5:
146239
{
147240
c=0;
148241
break;

0 commit comments

Comments
 (0)