【发布时间】: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