【发布时间】:2022-01-08 01:51:49
【问题描述】:
我需要用 txt 文件制作一个二叉树。每行描述一个节点: X Y - 其中 X 是一个字符值,Y 是一个描述方向的字符串。例如: C RRL - 节点有一个值'C'并且从根右(R)、右(R)、左定位
输出必须是从树的单词创建的最后一个字母单词。该程序不能使用集合或任何其他“现成的”Java 解决方案(流等)。此外,它必须具有 O(nlogn) 的平均时间复杂度和 O(n) 的内存复杂度。
示例:
输入
G RR
A
C L
F LLR
X LLL
F R
X RL
H LL
输出
XHCA
我目前有可以构造树的代码,但前提是节点从根开始按顺序排列。它不能像“想象”追随它不存在的根。所以只有树的开头是正确的。
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("fileInput.txt");
BinaryTree bt = new BinaryTree();
try(BufferedReader br = new BufferedReader(new FileReader(file))){
String line;
while ((line = br.readLine()) != null){
if(line.length()==1) {
bt.direction = "";
}
else
bt.direction = line.substring(2);
bt.add(line.charAt(0));
}
}
}
static class BinaryTree {
Node root;
String direction;
public void add(char letter){
if(direction.isBlank())
root = new Node(letter);
else
root = addRecursive(root, letter, 0);
}
private Node addRecursive(Node current, char letter, int j) {
if (current == null) {
return new Node(letter);
}
if(j < direction.length()){
if(direction.charAt(j)=='L'){
current.left = addRecursive(current.left, letter, ++j);
}
else if (direction.charAt(j)=='R') {
current.right = addRecursive(current.right, letter, ++j);
}
}
return current;
}
}
}
static class Node {
char letter;
Node left;
Node right;
Node(char letter) {
this.letter = letter;
left = null;
right = null;
}
}
}
【问题讨论】:
-
为什么输出以
X而不是H开头? -
它以 X 开头,因为我们正在寻找最后一个字母单词。由于 X 位于最左侧 (LLL),我们从它开始
标签: java tree time-complexity binary-tree