【问题标题】:Program to make a binary tree out of a text file用文本文件生成二叉树的程序
【发布时间】: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


【解决方案1】:

您可以读取集合中的所有值,然后按方向长度对其进行排序,然后循环遍历它并构建一棵树。

初读

G RR
A
C L
F LLR
X LLL
F R
X RL
H LL

然后按Y长度排序

A
C L
F R
X RL
H LL
G RR
F LLR
X LLL

然后构建你的树,或者用一些算法分析最后的节点,以将它们按正确的顺序排列。

【讨论】:

  • Soryy,不得不补充一点,我不能使用集合 :(
  • 数组呢?
  • 是的,我可以使用数组,但在不知道文件大小的情况下,我想不出一个解决方案来填充它。
  • 您可以先查看文件大小。或者您可以创建一个长度为 10 的数组,如果行数超过 10 行,您将创建一个长度为 10*2 的新数组,将前一个数组中的所有值放在这里并从位置 10 继续填充它。如果有超过 20 行,你创建一个大小为 20*2 的新数组,将前一个中的所有数据转移到这里并继续,......但是在这种情况下,您应该计算在单独变量中读取的行数。
  • 是的,这可以工作,但我认为不幸的是它会超过复杂性:/
猜你喜欢
  • 1970-01-01
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
  • 2015-03-04
  • 1970-01-01
  • 2021-10-10
  • 2020-06-26
相关资源
最近更新 更多