sample1 input:
4
1 2 4
2 0 3
3 0 0
4 0 0
sample1 output:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2da45d689d326439954e2a7131854ef7.png)
sample2 input:
7
5 4 3
4 2 1
3 7 9
2 0 0
1 0 0
7 0 0
9 0 0
sample2 output:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/044b2cb7de3a064e9bb23463ef668ab5.png)
AC代码
#include <stdio.h>
#define maxn 100
typedef struct
{
int parent;
int left;
int right;
}Node;
int findroot(Node T[])
{
int root=1;
while(T[root].parent!=-1)
{
root=T[root].parent;
}
return root;
}
void PreOrder(Node T[],int root)
{
if(root!=0)
{
printf("%d ",root);
PreOrder(T,T[root].left);
PreOrder(T,T[root].right);
}
}
void MidOrder(Node T[],int root)
{
if(root!=0)
{
MidOrder(T,T[root].left);
printf("%d ",root);
MidOrder(T,T[root].right);
}
}
void PostOrder(Node T[],int root)
{
if(root!=0)
{
PostOrder(T,T[root].left);
PostOrder(T,T[root].right);
printf("%d ",root);
}
}
void LevelOrder(Node T[],int root)
{
int Q[maxn];
int front=-1,rear=-1,p;
Q[++rear]=root;
while(front<rear)
{
p=Q[++front];
printf("%d ",p);
if(T[p].left)Q[++rear]=T[p].left;
if(T[p].right)Q[++rear]=T[p].right;
}
}
int main()
{
freopen("input.txt","r",stdin);
int n;
int a,b,c,root;
scanf("%d",&n);
Node T[n+1];
for(int i=1;i<=n;i++)
T[i].parent=-1;
while(scanf("%d %d %d",&a,&b,&c)!=EOF)
{
T[a].left=b;
T[a].right=c;
T[b].parent=a;
T[c].parent=a;
}
root=findroot(T);
printf("前序遍历为:");
PreOrder(T,root);
printf("\n");
printf("中序遍历为:");
MidOrder(T,root);
printf("\n");
printf("后序遍历为:");
PostOrder(T,root);
printf("\n");
printf("水平遍历为:");
LevelOrder(T,root);
}