【发布时间】:2021-12-29 20:12:38
【问题描述】:
我正在尝试在 BST 中实现插入方法,但遇到了一些问题。给定周围的代码:
public class BinarySearchTree<E> {
private BinaryNode<E> root;
private int size;
private Comparator<E> comparator;
/**
* Constructs an empty binary search tree, sorted according to the specified comparator.
*/
public BinarySearchTree(Comparator<E> comparator) {
root = null;
size = 0;
this.comparator = comparator;
}
private static class BinaryNode<E> {
private E element;
private BinaryNode<E> left;
private BinaryNode<E> right;
private BinaryNode(E element) {
this.element = element;
left = right = null;
}
}
//Other methods
}
我的实现有什么问题:
/**
* Inserts the specified element in the tree if no duplicate exists.
* @param x element to be inserted
* @return true if the the element was inserted
*/
public boolean add(E x) {
return add(root, x);
}
private boolean add(BinaryNode<E> n, E x) {
if(n == null) {
n = new BinaryNode<E> (x);
size++;
return true;
}
int compResult = comparator.compare(x, n.element);
if(compResult<0){
return add(n.left, x);
} else if(compResult>0) {
return add(n.right, x);
}else {
return false;
}
}
在测试仅插入一个元素时,我得到 null 作为根的返回值,但我真的看不出出了什么问题。感谢您的帮助!
【问题讨论】:
-
你想告诉我们什么是 null 还是我们应该只是猜测?
-
请以某种方式标记返回 null 的行。
-
只插入一个元素时,根的返回值为null。
-
我通过 JUnit 测试它。
assertTrue(bstNbrs.add(2), "Should return true when adding non duplicate");其中 bstNbrs 只是具有整数值的 bst。然后我做:assertEquals(2, bstNbrs.root.element, "Not correct order");。我有点作弊,因为我删除了属性的私有以便能够访问属性,但我这样做是为了能够测试。
标签: java algorithm recursion data-structures binary-search-tree