数据结构作业——order(二叉树遍历)
order
Description
给出一棵二叉树的中序遍历和每个节点的父节点,求这棵二叉树的先序和后 序遍历。
Input
输入第一行为一个正整数 n 表示二叉树的节点数目, 节点编号从 1 到 n,其中 1 为根节点。
第 2 行有 n 个数字, 第 i 个数字表示 i 的父亲节点。( 1 的父亲节点为 0, 表示无)
第 3 行为中序遍历。
30%的数据: n<=20;
60%的数据: n<=1000;
100%的数据: n<=10000;
Output
输出 2 行, 第一行为先序遍历,第二行为后序遍历。
Sample Input
10
0 7 2 2 9 1 8 1 6 8
9 5 6 1 10 8 7 3 2 4
Sample Output
1 6 9 5 8 10 7 2 3 4
5 9 6 10 3 4 2 7 8 1
思路
存下每个节点的左右儿子,然后根据中序遍历判断谁是左儿子,谁是右儿子,建完树,跑一下先序遍历和后序遍历
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 10005;
int lson[maxn],rson[maxn],pos[maxn];
bool first = true;
void PreOrder(int x)
{
if (x != 1) printf(" ");
printf("%d",x);
if (lson[x]) PreOrder(lson[x]);
if (rson[x]) PreOrder(rson[x]);
}
void PostOrder(int x)
{
if (lson[x]) PostOrder(lson[x]);
if (rson[x]) PostOrder(rson[x]);
first?printf("%d",x):printf(" %d",x);
first = false;
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int N,i,tmp;
memset(lson,0,sizeof(lson));
memset(rson,0,sizeof(rson));
memset(pos,0,sizeof(pos));
scanf("%d",&N);
for (i = 1;i <= N;i++)
{
scanf("%d",&tmp);
if (tmp == 0) continue;
if (!lson[tmp]) lson[tmp] = i;
else rson[tmp] = i;
}
for (i = 1;i <= N;i++)
{
scanf("%d",&tmp);
pos[tmp] = i;
}
for (i = 1;i <= N;i++)
{
if (lson[i] && rson[i])
{
if (pos[rson[i]] < pos[lson[i]])
{
swap(rson[i],lson[i]);
}
}
else if (!lson[i] && rson[i])
{
if (pos[rson[i]] < pos[i])
{
lson[i] = rson[i];
rson[i] = 0;
}
}
else if (lson[i] && !rson[i])
{
if (pos[lson[i]] > pos[i])
{
rson[i] = lson[i];
lson[i] = 0;
}
}
}
PreOrder(1);printf("\n");
PostOrder(1);printf("\n");
return 0;
}
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆

浙公网安备 33010602011771号