【问题标题】:Binary Search Tree, In-order transversal return generic array二叉搜索树,按顺序横向返回泛型数组
【发布时间】:2022-01-01 14:47:03
【问题描述】:
public class Bst<E extends Comparable<E>> {

private BstNode<E> root;

    public Bst(E data) {
       root = new BstNode<>(data);
    }

    public void add(E data) {
        root = arr(data,root);
    }

    private BstNode<E> add(E data, BstNode<E> startNode) {
        if (startNode == null) {
            startNode = new BstDupNode<>(data);
        } else if (data.compareTo(startNode.data) < 0) {
            startNode.left = add(data, startNode.left);
        } else {
            startNode.right = add(data, startNode.right);
        }
        return startNode;
    }
   
    public E[] getAllData(E[] template) {
        index = 0;
        inorderTraversal(template, root, index);
        return template;
    }

    private int index;

    private void inorderTraversal(E[] template, BstNode<E> startNode, int index) {
        if (startNode != null) {
            inorderTraversal(template,startNode.left, index);
            template[index++] = startNode.data;
            inorderTraversal(template, startNode.right, index);
        }
    }


    private static class BstNode<E extends Comparable<E>> {
        public int count;
        public E data;
        public BstNode<E> left , right;

        public BstDupNode(E data) {
            this.data = data;
            left = right = null;
        }
    }

    public static void main(String[] args) {
        Bst<Integer> hello = new BstDup<>(7);
        hello.add(8);
        hello.add(3);
        hello.add(1);
        hello.add(6);
        hello.add(4);
        hello.add(10);
        hello.add(14);
   }
}

我得到了类似的结果

[7, 8, 10, 14, null, null, null, null, null, null, null]

我不知道为什么不时将索引设置回零。因为自从我设置了全局变量,它应该随着隐居继续计数,或者至少我是这么认为的。如果您能提供一些解释,我想最终理解不仅仅是回答,我将不胜感激。谢谢。

【问题讨论】:

  • 你的代码是否完整? hello.add 是什么?
  • 很抱歉。我正要编写 main 方法,但我改变主意并从我的代码中复制了它。
  • 这仍然令人困惑。 root 在哪里?为什么BstDup 有add 方法?它扩展了一个类吗?结果在哪里打印?您应该提供完整的代码。
  • 我不知道为什么我需要提供添加方法,但你去吧。我给你打的。

标签: java generics recursion binary-search-tree inorder


【解决方案1】:

Java 使用 pass-by-value,这意味着方法获取其参数的 值,但这些与调用者的副本是分开的;因此,当您重新分配方法参数时,调用者不会看到该重新分配。

例如这样的方法:

void increment(int i) {
    ++i;
}

没有任何效果:该方法增加了i 的副本,但没有使用该副本。

在您的情况下,问题在于您的 inorderTraversal 方法采用参数 index 的值 - 所以它有自己的副本 - 然后它增加该副本,这很好,但它的调用者永远不会看到这种变化.

要解决此问题,我建议让 inorderTraversal 返回更新后的 index:

    private int inorderTraversal(E[] template, BstNode<E> startNode, int index) {
        if (startNode != null) {
            index = inorderTraversal(template,startNode.left, index);
            template[index++] = startNode.data;
            index = inorderTraversal(template, startNode.right, index);
        }
        return index;
    }

【讨论】:

  • 修复后,我什至不需要全局变量。也感谢您的清晰解释。
  • @lolo:不客气!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
相关资源
最近更新 更多