树转换为二叉树

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

Sample Output

rawxdhebfcsimonjtu
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;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值