当前位置: 首页 > article >正文

天梯赛 L2-011 玩转二叉树

和上面一道树的题思路一样,只需要换一下递归的顺序即可。

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
// #define int long long
typedef long long ll;
const int N = 50;
int n;
int a[N],b[N];
struct nod{
	int value;
	nod* l = NULL;
	nod* r = NULL;
};
nod* build(int al,int ar,int bl,int br){
	if(al > ar) return NULL;
	nod* root = (nod*)malloc(sizeof(nod));
	root->value = a[al];
	int x = a[al];
	int p = bl;
	while(b[p] != x){
		p++;
	}
	int len = p - bl;
	root->l = build(al+1,al+len,bl,p-1);
	root->r = build(al+len+1,ar,p+1,br);
	return root;
}
void bfs(nod* x){
	queue<nod> q;
	q.push(*x);
	while(!q.empty()){
		nod tmp = q.front();
		q.pop();
		if(tmp.value != x->value) cout<<" ";
		cout<<tmp.value;
		if(tmp.r != NULL) q.push(*(tmp.r));
		if(tmp.l != NULL) q.push(*(tmp.l));
	}
}
void solve() {
	cin>>n;
	for(int i = 1 ; i <= n ; i++){
		cin>>b[i];
	}
	for(int i = 1 ; i <= n ; i++){
		cin>>a[i];
	}
	nod* head = build(1,n,1,n);
	bfs(head);	//输出
}
int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int tt = 1;
    // cin >> tt;
    while (tt--) {
        solve();
    }
    return 0;
}


http://www.kler.cn/a/593990.html

相关文章:

  • 【MyDB】7-客户端服务端通信之3-Client的实现
  • AI日报 - 2025年3月21日
  • 使用FastAPI为知识库问答系统前端提供后端功能接口
  • 期货和期权的区别,通俗易懂!
  • ccf3401矩阵重塑(其一)
  • deepseek使用记录24——小灵
  • Spring 事务注解原理
  • [Xilinx]工具篇_Vivado自动安装
  • 计算机网络快速入门
  • 【C#知识点详解】ExcelDataReader介绍
  • 记一次性能调优-20250320
  • 【嵌入式硬件】 天线与距离问题
  • JVM常用概念之压缩引用
  • C语言的setjmp和longjmp:可以作异常处理
  • 【数据分享】2000—2024年我国乡镇的逐月归一化植被指数(NDVI)数据(Shp/Excel格式)
  • 微信小程序面试内容整理-请求优化
  • 经典面试题:C/C++中static关键字的三大核心作用与实战应用
  • 计算机四级 - 数据库原理(操作系统部分)- 第4章「并发与同步」
  • Numpy broadcasting规则
  • 3.20学习总结 java面向对象+string函数