BUAA 2014级数据结构第五次上机 二叉树之数组转换广义表

时间:2024-06-03 11:06:26

按题意建立好二叉树,再按照先序遍历输出结果。

#include<cstdio>
#include<vector>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std; struct node
{
int left, right, date; }node[]; int a[], flag[]; void dfs(int father)
{
printf("%d", node[father].date);
if (node[father].left != - || node[father].right != -) printf("(");
if (node[father].left != - && node[father].right == -)
{
dfs(node[father].left);
printf(")");
}
else if (node[father].left == - && node[father].right != -)
{
printf(",");
dfs(node[father].right);
printf(")");
}
else if (node[father].left != - && node[father].right != -)
{
dfs(node[father].left);
printf(",");
dfs(node[father].right);
printf(")");
} } int main()
{
int n, i;
while (~scanf("%d", &n))
{
int numm = ;
for (i = ; i <= ; i++)
{
node[i].date = -;
node[i].left = -;
node[i].right = -;
}
memset(flag, , sizeof(flag));
for (i = ; i <= n; i++) scanf("%d", &a[i]);
int father = , jishu = ;
node[numm].date = a[]; numm++;
for (i = ; i <= n; i++)
{
if (jishu == )
{
jishu++;
if (a[i] != -)
{
node[father].left = numm;
node[numm].date = a[i];
numm++;
}
}
else if (jishu == )
{
if (a[i] != -)
{
node[father].right = numm;
node[numm].date = a[i];
numm++;
}
jishu = ;
father++;
}
}
dfs();
printf("\n");
}
return ;
}