-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path二叉树按行遍历.cpp
executable file
·97 lines (84 loc) · 1.42 KB
/
二叉树按行遍历.cpp
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
#include<stdio.h>
#include<sys/malloc.h>
#include<string.h>
typedef struct node
{
char ch;
node *lchild;
node *rchild;
node *next;
}node,*tree;
typedef struct
{
node *front;
node *rear;
}list;
void in(list *l,node *p)
{
l->rear->next=p;
l->rear=p;
}
node *out(list *l)
{
node *p;
p=l->front->next;
l->front->next=p->next;
if(p==l->rear){l->rear=l->front;}
return p;
}
//void out(list *l,tree *p)//或者用这种方法出去,想要改变地址就必须用二级指针
//{
//*p=l->front->next;
//l->front->next=(*p)->next;
//if((*p)==l->rear){l->rear=l->front;}
//}
void creat(tree *root)
{
char ch;
ch=getchar();
if(ch==' '){root=NULL;}
else
{
(*root)=(node *)malloc(sizeof(node));
(*root)->ch=ch;
(*root)->lchild=(*root)->rchild=NULL;
creat(&((*root)->lchild));
creat(&((*root)->rchild));
}
}
void preprint(node *root)
{
if(root)
{
printf("%c",root->ch);
preprint(root->lchild);
preprint(root->rchild);
}
}
void rowprint(node *root,list *l)
{
node *r;
in(l,root);
while(l->front!=l->rear)
{
r=out(l);
printf("%c",r->ch);
if(r->lchild){in(l,r->lchild);}
if(r->rchild){in(l,r->rchild);}
}
}
int main()
{
list L;
node *s;
s=(node*)malloc(sizeof(node));
tree R;
creat(&R);
printf("先序遍历为");
preprint(R);
printf("\n");
L.front=L.rear=s;
printf("按层遍历为");
rowprint(R,&L);
return 0;
}