当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Dynamic linking of virtual machine stack of JVM

JVM之对象的内存布局

A 3D Dual Path U-Net of Cancer Segmentation Based on MRI

容器

How to traverse objects in the vector container

Flutter 基础组件之 Container

Install and configure redis in the Linux environment, and set the boot auto start

Fully Automated Gross Tumor Volume Delineation From PET in Head and Neck Cancer Using Deep Learning

Codeforces Round #659 (Div. 2)

力扣94二叉树的中序遍历
随机推荐
Dynamic linking of virtual machine stack of JVM
JVM method return address
我想要股票开户优惠,怎么得到?还有,在线开户安全么?
2019.11.3学习总结
setInterval、setTimeout和requestAnimationFrame
JVM之TLAB
Middle order traversal of Li Kou 94 binary tree
Wechat applet rewrites the page function to realize global logging
If I were in Beijing, where would it be better to open an account? In addition, is it safe to open an account online now?
Wechat applet realizes store function
Student addition / deletion gaih
Flutter 基础组件之 GridView
Causes and solutions of error reporting by using startactivity() method outside the activity
RecyclerView刷新闪烁与删除Item时崩溃问题
信号作品:时变和时不变
聊聊你理解的线程与并发
2019.10.30学习总结
C语言中通过sprintf()函数构造sql语句
JVM instructions for four call methods
51nod1277 字符串中的最大值【KMP】