当前位置:网站首页>二叉搜索树(DAY 75)
二叉搜索树(DAY 75)
2022-07-25 06:01:00 【张学恒】
1:题目
输入一系列整数,利用所给数据建立一个二叉搜索树,并输出其前序、中序和后序遍历序列。
输入格式
第一行一个整数 n,表示输入整数数量。
第二行包含 n 个整数。
输出格式
共三行,第一行输出前序遍历序列,第二行输出中序遍历序列,第三行输出后序遍历序列。
输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
数据范围
1≤n≤100,
输入元素取值范围 [1,1000]。
输入样例:
5
1 6 5 9 8
输出样例:
1 6 5 9 8
1 5 6 8 9
5 8 9 6 1
2:代码实现
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n;
int l[N], r[N], w[N], idx;
int root;
void insert(int& u, int x)
{
if (!u) u = ++ idx, w[u] = x;
else if (x < w[u]) insert(l[u], x);
else if (x > w[u]) insert(r[u], x);
}
void dfs(int u, int t)
{
if (!u) return;
if (t == 0) cout << w[u] << ' ';
dfs(l[u], t);
if (t == 1) cout << w[u] << ' ';
dfs(r[u], t);
if (t == 2) cout << w[u] << ' ';
}
int main()
{
cin >> n;
while (n -- )
{
int x;
cin >> x;
insert(root, x);
}
for (int i = 0; i < 3; i ++ )
{
dfs(root, i);
cout << endl;
}
return 0;
}
边栏推荐
- 2020ICPC 江西省赛热身赛 E.Robot Sends Red Packets(dfs)
- "Everyday Mathematics" serial 61: March 1
- 剑指 Offer 54. 二叉搜索树的第k大节点
- Leetcode 0121. the best time to buy and sell stocks - simulation from back to front
- Talk about how redis handles requests
- Softing pngate series gateway: integrate PROFIBUS bus into PROFINET network
- Brief introduction of acoustic filter Market
- HTB-Beep
- Pdf snapshot artifact
- How to start if you want to be a product manager?
猜你喜欢

HTB-Devel

Sword finger offer 36. binary search tree and bidirectional linked list

What are the ways to realize web digital visualization?

Leetcode 204. count prime numbers (wonderful)

Blocking Queue Analysis

Xiaomi 12s UTRA Leica watermark generation online tool

新时代生产力工具——FlowUs 息流全方位评测

How to play a data mining game entry Edition

Brief introduction of acoustic filter Market

(2022 Niuke multi School II) k-link with bracket sequence I (dynamic planning)
随机推荐
Xiaomi 12s UTRA Leica watermark generation online tool
(2022年牛客多校一)I-Chiitoitsu(期望DP)
线性代数(三)
(2022 Niuke multi school) D-Link with game glitch (SPFA)
QT qtextedit setting qscrollbar style sheet does not take effect solution
HTB-Arctic
R language uses data.table function to create data.table data (use: operator to create continuous numeric vector)
Adaptation dynamics | in June, sequoiadb completed mutual certification with five products
(15) [driver development] over written copy
剑指 Offer 36. 二叉搜索树与双向链表
10. Rendering Basics
Draw Bezier curve through screen interaction
Mechanism and principle of multihead attention and masked attention
sqlilabs less-29
A little experience about von Mises distribution
npx和npm区别
新时代生产力工具——FlowUs 息流全方位评测
Sword finger offer 36. binary search tree and bidirectional linked list
(牛客多校二)J-Link with Arithmetic Progression(最小二乘法/三分)
Vim配置Golang开发环境