当前位置:网站首页>PTA: 浪漫倒影 [二叉树重建] [深度优先遍历]
PTA: 浪漫倒影 [二叉树重建] [深度优先遍历]
2022-04-23 02:05:00 【JackDawn!?】
题目
输入样例:
8
6 8 7 4 5 1 3 2
8 5 4 7 6 3 2 1
输出样例:
R: 1 2 3 4 5
L: 1 6 7 8 5
思路
重建二叉树,然后深度优先遍历,如果是看右视图,就优先遍历右子树;如果是左视图,就优先遍历左子树。遍历过程中记录每个深度是否有节点已经被看到,打印出第一个被看到的节点。
代码
#include <cstdio>
#include <cstring>
using namespace std;
struct node {
int n;
node* l, *r;
node() {
l = r = NULL;
}
};
int last[25], mid[25];
node* build(int mb, int me, int lb, int le) {
if(mb > me || lb > le) return NULL;
node* t = new node();
t->n = last[le];
int m;
for(int i = mb; i <= me; ++i) {
if(mid[i] == last[le]) {
m = i;
break;
}
}
int ls = m-mb;
t->l = build(mb, m-1, lb, lb+ls-1);
t->r = build(m+1, me, lb+ls, le-1);
return t;
}
bool vis[20];
void right(node* tree, int depth) {
if(tree) {
if(!vis[depth]) {
printf(" %d", tree->n);
vis[depth] = true;
}
right(tree->r, depth+1);
right(tree->l, depth+1);
}
}
void left(node* tree, int depth) {
if(tree) {
if(!vis[depth]) {
printf(" %d", tree->n);
vis[depth] = true;
}
left(tree->l, depth+1);
left(tree->r, depth+1);
}
}
int main(void)
{
freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%d", &mid[i]);
}
for(int i = 0; i < n; ++i) {
scanf("%d", &last[i]);
}
node* tree = build(0, n-1, 0, n-1);
memset(vis, 0, sizeof(vis));
printf("R:");
right(tree, 0);
printf("\n");
memset(vis, 0, sizeof(vis));
printf("L:");
left(tree, 0);
return 0;
}
版权声明
本文为[JackDawn!?]所创,转载请带上原文链接,感谢
https://blog.csdn.net/apple_52296856/article/details/124315805
边栏推荐
- JDBC cannot connect to MySQL, and the error is access denied for user 'root' @ '* * *' (using password: Yes)
- What categories do you need to know before using proxy IP?
- EBS:PO_ EMPLOYEE_ HIERARCHIES_ ALL
- 浅析静态代理ip的三大作用。
- Uncover floating-point operations hidden by the ARM compiler
- Leetcode40 - total number of combinations II
- keil mdk中文乱码,两种解决方法,字体不再难看
- 搭建网站是用物理机还是云主机好?
- 什么是bgp服务器,有哪些优势?
- C语言中如何“指名道姓”的进行初始化
猜你喜欢
随机推荐
On LAN
Esp32 message queue using FreeRTOS
如何设置电脑ip?
keil mdk中文乱码,两种解决方法,字体不再难看
Is CICC fortune a company with CICC? Is it safe
什么是bgp服务器,有哪些优势?
用TensorFlow实现线性回归(包括过程中出现的问题及解决方法)
Open3d point cloud processing
How to change the size of SVG pictures without width in openlayer
Dynamic memory management
OJ daily practice - Finish
Find the largest number of two-dimensional arrays
拨号vps会遇到什么问题?
How to initialize "naming and surname" in C language
Implementation of Base64 encoding / decoding in C language
Thinkphp内核开发盲盒商城源码v2.0 对接易支付/阿里云短信/七牛云存储
使用代理IP是需要注意什么?
[tutorial] how to use GCC "zero assembly" for white whoring MDK
J-Link RTT使用
Realize linear regression with tensorflow (including problems and solutions in the process)