【问题标题】:Need helping printing a recursion [duplicate]需要帮助打印递归[重复]
【发布时间】:2017-03-31 12:08:59
【问题描述】:
BST(T[] array) {
    constructBalancedTree(array, 0, array.length - 1);

}
void constructBalancedTree(T[] array, int i, int j) {
    if(i > j) {
        return;
    }

    int mid = (i+j)/2;
    Node node = new Node(array[mid]);

    constructBalancedTree(array, i, mid-1);
    constructBalancedTree(array, mid+1, j);
}

我正在尝试弄清楚如何将其打印出来。我已经创建了:

BST<Integer> t1 = new BST<Integer>(new Integer[] {1, 5, 9, 12, 13, 15})

但是当我尝试打印出来时,它给了我一个参考

【问题讨论】:

  • 您没有在代码中的任何地方打印。
  • Whats a Node 这里也没有定义。你想把结果保存在哪里?
  • BST t1 = new BST(new Integer[] {1, 5, 9, 12, 13, 15})
  • 这就是我的主要内容,我无法打印出“System.out.println(t1);”它只是给了我一个参考错误。
  • 这是 Object 的默认行为,在你的类中覆盖 toString()

标签: java


【解决方案1】:

您需要遍历数组以打印其中的元素。在 Java 中,Array 是一个对象,因此在您的情况下 System.out.println(t1); 将打印对该对象的引用。试试

for(int i = 0; i < t1.length(); i++) {
    System.out.println(t1[i]);
 }

【讨论】:

  • 你不应该在 main 中使用 for 循环。
  • 我认为 OP 意味着在从数组构造树之后打印树。
  • 是的。如果有帮助,这是我的完整代码:pastebin.com/9SYJ584f
  • @keving 此循环仅用于在您从方法返回数组后打印出数组值。
【解决方案2】:

我真的不明白你的代码应该做什么。它似乎没有将节点存储在任何地方。我希望constructBalancedTree 应该返回一个节点,不是吗?比如:

class BST {
    private Node root;

    BST(T[] array)  {
        root = constructBalancedTree(array, 0, array.length - 1);
    }

    private Node constructBalancedTree(T[] array, int i, int j) {
        if(i > j) {
            return null;
        } else {
            int mid = (i+j)/2;
            Node node = new Node(array[mid]);
            node.setLeft(constructBalancedTree(array, i, mid-1));
            node.setRight(constructBalancedTree(array, mid+1, j));
            return node;
        }
    }
}

在打印树方面,您有很多选择。您可以添加一个递归打印子节点的toString 方法;您可以使用访问者设计模式来访问所有节点;你可以有一个方法以列表或流的形式获取值:

class Node<T> {
    private Node left;
    private Node right;
    private T value;

    public Stream<T> getValues() {
        Stream.Builder<T> values = Stream.builder();
        if (left != null)
            left.getValues().forEach(values::accept);
        values.accept(value);
        if (right != null)
            right.getValues().forEach(values::accept);
        return values.build;
    }
}

然后您可以打印这些值:System.out.println(root.getValues().collect(Collectors.joining(", "))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2016-11-15
    • 2010-10-21
    • 2011-05-31
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多