我正在尝试使用 insert() 填充二叉搜索树,但是当我每次“打印”我的 BST 的内容时,我只会得到插入到 BST 中的最后一项。我需要解决什么问题才能确保我的所有价值都保留在 BST 中?
从调试中,我认为我的问题是我的 public void insert() 每次调用它时都会将新值设置为 root。我不知道如何解决它?
这是我的 BST 课程:
public class BinarySearchTree<T extends Comparable<T>> {
private class BinarySearchTreeNode<E>{
public BinarySearchTreeNode<E> left, right;
private E data;
private BinarySearchTreeNode (E data) {
this.data = data;
}
}
private BinarySearchTreeNode<T> root;
public boolean isEmpty() {
return root == null;
}
private BinarySearchTreeNode<T> insert(T value, BinarySearchTreeNode<T> ptr) {
if (ptr == null){
ptr = new BinarySearchTreeNode<>(value);
return ptr;
}
int compare = value.compareTo(ptr.data); //when ptr != null, this line and below should execute for each bstStrings.inster(x)
/* pass the value (s1...sN) when compared to (ptr.data) to compare
* when value and ptr.data == 0 re
*/
if (compare == 0) {
return ptr;
}
if (compare < 0) {
while (ptr.left != null){
ptr = ptr.left;
if (ptr.left == null) {//found insertion point
BinarySearchTreeNode<T> node = new BinarySearchTreeNode<>(value);
ptr = ptr.left;
ptr = node;
return ptr;
}
}
}
else {
return insert(value, ptr.left);
}
if (compare > 0) {
if (ptr.right == null) {
BinarySearchTreeNode<T> node = new BinarySearchTreeNode<>(value);
ptr = ptr.right;
ptr = node;
return ptr;
}
}
else {
return insert(value, ptr.right);
}
return ptr;
}
public void insert(T value) {
root = insert(value, root); //****Where I believe the problem is******
}
private void printTree(BinarySearchTreeNode<T>node){
if(node != null){
printTree(node.left);
System.out.println(" " + node.data);
printTree(node.right);
}
}
public void printTree(){
printTree(root);
System.out.println();
}
}
对于添加上下文,这里是我的 Main(),我在其中调用 insert() 并尝试将字符串插入 BST:
public class Main {
public static void main(String[] args) {
BinarySearchTree<String> bstStrings = new BinarySearchTree<String>();
String s = "Hello";
String s1 = "World";
String s2 = "This Morning";
String s3 = "It's";
bstStrings.insert(s);
bstStrings.insert(s1);
bstStrings.insert(s2);
bstStrings.insert(s3); //the only inserted value that is printed below
bstStrings.printTree();
System.out.println();
System.out.println("You should have values above this line!");
}
}
最后我的控制台输出:
It's
You should have values above this line!