当前位置:网站首页>二叉搜索树解决落叶问题
二叉搜索树解决落叶问题
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;
}六 测试
绿色为输入,白色为输出。

边栏推荐
- Optimize the query (work in progress)
- Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
- navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication
- 剑指offer第22题-链表中倒数第K个节点
- 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
- Makefile
- 嵌入式系统:时钟
- override学习(父类和子类)
- Cloud platform construction solutions
- 趣链的产品构架
猜你喜欢
随机推荐
golang写的存储引擎,基于b+树,mmap
什么是memoization,它有什么用?
472. Concatenated Words
Codeup刷题笔记-简单模拟
Websocket multi-threaded sending message error TEXT_PARTIAL_WRITING--Use case of spin lock replacing synchronized exclusive lock
[b01lers2020]Life on Mars
Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
HDU 5655 CA Loves Stick
Testng listener
utlis 线程池
关于IDO预售系统开发技术讲解丨浅谈IDO预售合约系统开发原理分析
Golang第二章:程序结构
for loop exercises
The development status of cloud computing at home and abroad
Nine ways to teach you to read the file path in the resources directory
Quickly build a website with static files
HCIP BGP实验报告
伴随着元宇宙、web3.0等概念的兴起,数字人、数字场景等诸多数字化的形态开始出现
云计算国内外发展现状
websocket多线程发送消息报错TEXT_PARTIAL_WRITING--自旋锁替换synchronized独占锁的使用案例









