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

天梯赛 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;
}

相关文章:

  • 使用uniapp的vite版本进行微信小程序开发,在项目中使用mqtt连接、订阅、发布信息
  • 若依(RuoYi)框架新手使用指南
  • Bilve 搭建手册
  • L2TP的LAC拨号模式实验
  • 【SpringBoot】你不能不会的SpringBoot图形验证码生成
  • 自学Python创建强大AI:从入门到实现DeepSeek级别的AI
  • bootstrap介绍(前端框架)(提供超过40种可复用组件,从导航栏到轮播图,从卡片到弹窗)bootstrap框架
  • 1688商品数据实战:API搜索接口开发与供应链分析应用
  • Linux--进程创建
  • CTF类题目复现总结-[WUSTCTF2020]girlfriend 1
  • wpa_supplicant驱动初始化源码分析
  • Gin框架学习
  • 【sgFloatDialog】自定义组件:浮动弹窗,支持修改尺寸、拖拽位置、最大化、还原、最小化、复位
  • Vue3 在组件中判断事件是否注册
  • js原型链与自动装箱机制
  • 从OSI七层网络模型角度了解CAN通信协议
  • 关于金融开发领域的一些专业知识总结
  • jmeter接口测试[-面试篇-]
  • 【YOLOv8改进 - C2f融合】C2f融合SCConv :即插即用的空间和通道重建卷积
  • 我的uniapp自定义模板
  • 种植耐旱作物、启动备用水源,甘肃各地多举措应对旱情
  • 15年全程免费,内蒙古准格尔旗实现幼儿园到高中0学费
  • 中国首颗地质行业小卫星“浙地一号”成功发射
  • 阳光保险拟设立私募证券投资基金,总规模200亿元
  • 国家防汛抗旱总指挥部对15个重点省份开展汛前实地督导检查
  • 【社论】城市更新,始终以人为核心