当前位置:网站首页>二叉搜索树解决落叶问题
二叉搜索树解决落叶问题
2022-08-03 22:41:00 【chengqiuming】
一 原问题链接
Falling Leaves - POJ 1577 - Virtual Judgehttps://vjudge.net/problem/POJ-1577
二 输入和输出
1 输入
输入包含多个测试用例。每个测试用例都是一行或多行大写字母序列,每行都给出按上述步骤从二叉搜索树中删除的叶子,每行给出的字母都按字母升序排列。在测试用例之间以一行分隔,该行仅包含一个星号,在最后一个测试用例后给出一行,该行仅给出一个美元符号。在输入中没有空格或空行。
2 输出
对于每个测试用例,都有唯一的二叉搜索树,单行输出该树的先序遍历。
三 输入和输出样例
1 输入样例
BDHPY
CM
GQ
K
*
AC
B
$
2 输出样例
KGCBDHQMPY
BAC
四 算法设计
最后一个字母一定为树根,先输入的字母在树的深层,可以逆序建树。读入字母序列后用字符串存储,然后逆序创建二叉搜索树,将小的字母插入左子树,将大的字母插入右子树。输出该树的先序遍历:根,左子树,右子树。
五 代码
package poj1577;
import java.util.Scanner;
public class Poj1577 {
static int cnt = 1;
static data tree[] = new data[110];
static void insert(int t, char ch) {
if (tree[t].c == 0) {
tree[t].c = ch;
return;
}
if (ch < tree[t].c) {
if (tree[t].l == 0) {
tree[++cnt].c = ch;
tree[t].l = cnt;
} else
insert(tree[t].l, ch);
}
if (ch > tree[t].c) {
if (tree[t].r == 0) {
tree[++cnt].c = ch;
tree[t].r = cnt;
} else
insert(tree[t].r, ch);
}
}
static void preorder(int t) {
if (tree[t].c == 0)
return;
System.out.print(tree[t].c);
preorder(tree[t].l);
preorder(tree[t].r);
}
public static void main(String[] args) {
String s1, s;
while (true) {
s = "";
for (int i = 0; i < tree.length; i++) {
tree[i] = new data();
}
Scanner scanner = new Scanner(System.in);
while (true) {
s1 = scanner.next();
if (s1.charAt(0) != '*' && s1.charAt(0) != '$') {
s += s1;
} else {
break;
}
}
for (int i = s.length() - 1; i >= 0; i--)
insert(1, s.charAt(i));
preorder(1);
System.out.println();
if (s1.charAt(0) == '$')
break;
}
}
}
class data {
int l;
int r;
char c;
}
六 测试
绿色为输入,白色为输出。
边栏推荐
猜你喜欢
[b01lers2020]Life on Mars
noip preliminary round
21天打卡挑战学习MySQL——《Window下安装MySql》第一周 第三篇
Cloud platform construction solutions
PowerMockup 4.3.4::::Crack
Bytebase database schema change management tool
Click the icon in Canvas App to generate PDF and save it to Dataverse
CAS:178744-28-0,mPEG-DSPE,DSPE-mPEG,甲氧基-聚乙二醇-磷脂酰乙醇胺供应
[b01lers2020]Life on Mars
投资性大于游戏性 NFT游戏到底是不是门好生意
随机推荐
[b01lers2020]Life on Mars
Work Subtotal QT Packing
websocket多线程发送消息报错TEXT_PARTIAL_WRITING--自旋锁替换synchronized独占锁的使用案例
On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use
九种方式,教你读取 resources 目录下的文件路径
MiniAPI of .NET6 (14): Cross-domain CORS (Part 1)
What is the difference between the generator version and the viewer version?
Click the icon in Canvas App to generate PDF and save it to Dataverse
Embedded Systems: Clocks
伴随着元宇宙、web3.0等概念的兴起,数字人、数字场景等诸多数字化的形态开始出现
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
网络基础学习系列四(网络层,数据链路层和一些其他重要协议或技术)
优化查询(工作中)
藏宝计划TreasureProject(TPC)系统模式开发技术原理
480. Sliding Window Median
The development status of cloud computing at home and abroad
21天打卡挑战学习MySQL——《Window下安装MySql》第一周 第三篇
线上服务器老是卡,该如何优化?
物联网新零售模式,引领购物新潮流
Storage engine written by golang, based on b+ tree, mmap