Description
输入一颗普通有序树,将它转换为对应的二叉链表存储,然后输出该二叉树的先序和后序遍历序列。
Input
包含多组测试数据。每组测试数据第1行为树的结点个数n(1≤n≤26)。接下来包含n行,其中第i行(1≤n≤n)的数据依次为结点i的数据值ai(为一个小写字母),后面各元素为结点i的儿子序列,以0结束。若ai后仅含一个0,则表示结点i为叶子节点。
Output
输出包含2行,第一行为先序遍历序列,第二行为后序遍历序列。
Sample Input
18
r 2 3 4 0
a 5 6 0
b 7 0
c 8 9 10 0
w 0
x 11 12 0
f 0
s 13 14 0
t 0
u 0
d 15 0
e 0
i 16 17 18 0
j 0
h 0
m 0
o 0
n 0
r 2 3 4 0
a 5 6 0
b 7 0
c 8 9 10 0
w 0
x 11 12 0
f 0
s 13 14 0
t 0
u 0
d 15 0
e 0
i 16 17 18 0
j 0
h 0
m 0
o 0
n 0
Sample Output
rawxdhebfcsimonjtu
hedxwfnomjiutscbar
hedxwfnomjiutscbar
分析:树转化为二叉树,常用孩子兄弟表示法表示树,lchild指向第一个孩子,rchild指向该结点的下一个兄弟。
参考代码:
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<iostream>
using namespace std;
const int maxn = 30;
int n;
//孩子兄弟表示树
typedef struct TNode{
char data;
int parent;
int lchild;
int rchild;
}Tree;
Tree tree[maxn];
void preorder( Tree t[], int tmp)
{
if( tmp <= 0)
return;
printf("%c",t[tmp].data);
preorder( t,t[tmp].lchild);
preorder( t,t[tmp].rchild);
}
void postorder( Tree t[], int tmp)
{
if( tmp <= 0)
return;
postorder( t,t[tmp].lchild);
postorder( t,t[tmp].rchild);
printf("%c",t[tmp].data);
}
int main()
{
while( ~scanf("%d",&n))
{
for( int i = 1; i <= n; i++)
tree[i].parent = 0;
for( int i = 1; i <= n; i++)
{
getchar();//接受换行符
int tmp;
scanf("%c%d",&tree[i].data,&tmp);
tree[i].lchild = tmp;//lchild指向第一个节点 0为空 即本身为根节点
int a;
while( tmp)
{
tree[tmp].parent = i;//tmp的双亲为i
scanf("%d",&a);
tree[tmp].rchild = a;//a为tmp的兄弟
tmp = a;
}
}
int tmp = 0;
for( int i = 1; i <= n; i++)
{
if( tree[i].parent == 0)
{
tmp = i;
break;
}
}
tree[tmp].rchild = 0;//根节点没有兄弟
preorder(tree,tmp);
putchar(10);
postorder(tree,tmp);
putchar(10);
}
return 0;
}