PAT 1102. Invert a Binary Tree (25)

题意:给你一个n(n<=10), 表示有一颗n个节点的数,现在给你n行,第i行表示第i个节点的左右孩子,让你输出该树反转后的层序遍历和中序遍历。

思路:用个lch和rch分别记录每个点的左右孩子,给出的关系中肯定有一个节点不会出现,那个节点就是根节点。

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 1e3+5;
int lch[maxn], rch[maxn], n, root;
int q[maxn*2];
bool book[maxn];

void showLevel()
{
    int head = 1, tail = 0;
    q[++tail] = root;
    while(head <= tail)
    {
        int x = q[head++];
        if(x != root) printf(" ");
        printf("%d", x);
        if(lch[x] != -1) q[++tail] = lch[x];
        if(rch[x] != -1) q[++tail] = rch[x];
    }
    puts("");
}

int flag;

void showIn(int cur)
{
    if(lch[cur] != -1) showIn(lch[cur]);
    if(flag) printf(" ");
    printf("%d", cur);
    flag = 1;
    if(rch[cur] != -1) showIn(rch[cur]);
}

int main(void)
{
    while(cin >> n)
    {
        memset(lch, -1, sizeof(lch));
        memset(rch, -1, sizeof(rch));
        memset(book, 0, sizeof(book));
        for(int i = 0; i < n; i++)
        {
            char ch1, ch2;
            scanf(" %c %c", &ch1, &ch2);
            int l, r;
            if(ch1 == '-') l = -1;
            else l = ch1-'0', book[l] = 1;
            if(ch2 == '-') r = -1;
            else r = ch2-'0', book[r] = 1;
            lch[i] = l, rch[i] = r;
         }
        for(int i = 0; i < n; i++)
        {
            swap(lch[i], rch[i]);
            if(!book[i]) root = i;
        }
        showLevel();
        flag = 0;
        showIn(root);
        puts("");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值