题意:给你一个n(n<=10), 表示有一颗n个节点的数,现在给你n行,第i行表示第i个节点的左右孩子,让你输出该树反转后的层序遍历和中序遍历。
思路:用个lch和rch分别记录每个点的左右孩子,给出的关系中肯定有一个节点不会出现,那个节点就是根节点。
Sample Input:
8 1 - - - 0 - 2 7 - - - - 5 - 4 6Sample 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;
}
263

被折叠的 条评论
为什么被折叠?



