团体程序设计天梯赛-练习集 L2-011. 玩转二叉树 解题报告
2017-03-18 14:59
627 查看
L2-011. 玩转二叉树
时间限制400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7 1 2 3 4 5 6 7 4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
数组实现:
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
int in[50], pre[50], l[100], r[100], n;
int build(int inl, int inr, int prel, int prer)
{
if(prel > prer) return 0;
int rt = pre[prel], p1 = inl, p2;
while(in[p1] != rt) p1++;
p2 = p1 - inl;
l[rt] = build(inl, p1 - 1, prel + 1, prel + p2);
r[rt] = build(p1 + 1, inr, prel + p2 + 1, prer);
return rt;
}
void print(int rt)
{
queue<int> Q;
Q.push(rt);
while(!Q.empty())
{
int now = Q.front();
Q.pop();
if(now == rt) printf("%d", now);
else printf(" %d", now);
if(r[now] != 0) Q.push(r[now]);
if(l[now] != 0) Q.push(l[now]);
}
printf("\n");
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &in[i]);
for(int i = 0; i < n; i++) scanf("%d", &pre[i]);
build(0, n-1, 0, n-1);
print(pre[0]);
return 0;
}
链表实现:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
#define MAXN 50
int in[MAXN], pre[MAXN];
struct node
{
int v;
node *left;
node *right;
node(int v):v(v),left(NULL),right(NULL){}
};
node* build(node* &root, int inl, int inr, int prel, int prer)
{
if(inl > inr) return 0;
int rt = pre[prel], p = inl, cnt;
root = new node(rt);
while(in[p] != rt) p++;
cnt = p - inl;
root->left = build(root->left, inl, p - 1, prel + 1, prel + cnt);
root->right = build(root->right, p + 1, inr, prel + cnt + 1, prer);
return root;
}
void print(node* rt)
{
queue<node*> Q;
Q.push(rt);
while(!Q.empty())
{
node* now = Q.front();
Q.pop();
if(now->v != rt->v) printf(" ");
printf("%d", now->v);
if(now->right) Q.push(now->right);
if(now->left) Q.push(now->left);
}
printf("\n");
}
int main()
{
int n;
node *root;
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &in[i]);
for(int i = 0; i < n; i++) scanf("%d", &pre[i]);
build(root, 0, n-1, 0, n-1);
print(root);
return 0;
}
相关文章推荐
- 团体程序设计天梯赛-练习集 L2-011. 玩转二叉树
- 团体程序设计天梯赛-练习集L2-011. 玩转二叉树
- 团体程序设计天梯赛-练习集L2-011 玩转二叉树(构造二叉树+BFS)
- 团体程序设计天梯赛-练习集L2-011. 玩转二叉树
- 团体程序设计天梯赛-练习集 L2-008. 最长对称子串 解题报告
- 团体程序设计天梯赛-练习集 L2-009. 抢红包 解题报告
- L2-011. 玩转二叉树-PAT团体程序设计天梯赛GPLT
- 团体程序设计天梯赛-练习集 L2-004. 这是二叉搜索树吗? 解题报告
- 团体程序设计天梯赛-练习集 L2-010. 排座位 解题报告
- 团体程序设计天梯赛-练习集 L2-016. 愿天下有情人都是失散多年的兄妹 解题报告
- 团体程序设计天梯赛-练习集 L2-014. 列车调度 解题报告
- 团体程序设计天梯赛-练习集 L2-015. 互评成绩 解题报告
- L2-011. 玩转二叉树-PAT团体程序设计天梯赛GPLT
- 团体程序设计天梯赛-练习集 L2-012. 关于堆的判断 解题报告
- 团体程序设计天梯赛-练习集 L2-002. 链表去重 解题报告
- 团体程序设计天梯赛-练习集 L2-002 链表去重 解题报告
- 团体程序设计天梯赛-练习集 L2-013. 红色警报 解题报告
- 团体程序设计天梯赛-练习集 L2-001 紧急救援 dijkstra 解题报告
- 团体程序设计天梯赛-练习集 L2-003. 月饼 贪心 解题报告
- 团体程序设计天梯赛L2-011 玩转二叉树