当前位置:网站首页>1099 Build A Binary Search Tree (30 分)
1099 Build A Binary Search Tree (30 分)
2022-06-29 09:23:00 【陌陌623】
题解
好题!!!
如果我去年天梯赛之前就做过的话 真的是好题了
这个题和去年天梯L2的搜索树 有相似的地方
我去年还不怎么会建树 以为那个题可以退出来的
结果不是,是按着他给的一个遍历序列 在过一遍,以此填进去
这个题是给了二叉树的模板,那个题也差不多是给了
因为 那个题说的是完全二叉树
所以和给差不多
真·题解: 在二叉搜索树的性质中,中序遍历序列是顺序的
所以将给出的数据,排序,就是中序序列。
故,知道了中序序列和二叉树的样子,那么就可以得到整个二叉树
得到的过程就是一个基本的树的遍历
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int n = 110;
int N;
int a[n], l[n], r[n], d[n];
int ind;
void build(int k)
{
if (k == -1)
return;
build(l[k]);
d[k] = a[ind++];
build(r[k]);
}
void bfs()
{
queue<int> q;
q.push(0);
while (!q.empty())
{
int x = q.front();
q.pop();
if (x != 0)
cout << " ";
cout << d[x];
// cout << x << endl;
if (l[x] != -1)
q.push(l[x]);
if (r[x] != -1)
q.push(r[x]);
}
}
int main()
{
cin >> N;
int x, y;
for (int i = 0; i < N; i++)
{
cin >> x >> y;
l[i] = x;
r[i] = y;
}
for (int i = 0; i < N; i++)
cin >> a[i];
sort(a, a + N);
build(0);
bfs();
return 0;
}
边栏推荐
- JVM之方法返回地址
- Flutter 基础组件之 ListView
- EDA与VHDL题库
- 2020-09-29 非商品模板化代码层次 rapidjson库
- 时变和非时变
- Middle order traversal of Li Kou 94 binary tree
- nacos注册中心集群
- JS obtain mobile phone model and system version
- Language characteristics
- Caused by: org. apache. xerces. impl. io. MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8
猜你喜欢
随机推荐
RecyclerView刷新闪烁与删除Item时崩溃问题
聊聊你理解的线程与并发
FreeRTOS(八)——时间管理
SymPy Tutorial(译)
基辅周边的凄美废墟——切尔诺贝利的安全前往指南!
2020-09-23左右值 右值引用 std::move()
Wechat applet realizes store function
JVM之虚拟机栈之动态链接
leetcode MYSQL数据库题目178
我想知道如何免费网上注册股票开户?另外,手机开户安全么?
Wechat applet rewrites the page function to realize global logging
数据库常见面试题(附答案)
Memory layout of JVM objects
另类实现 ScrollView 下拉头部放大
RecyclerView 粘性(悬浮)头部
Is flush stock trading software reliable and safe?
IPC(进程间通信)之管道详解
ImageView picture fill problem
Codeforces Round #659 (Div. 2)
Caused by: org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8









