【问题标题】:BST Only Keeps Last Inserted Value and Makes it RootBST 仅保留最后插入的值并使其成为根
【发布时间】:2023-03-15 03:16:01
【问题描述】:

我正在尝试使用 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!

【问题讨论】:

  • 我在insert 中看不到任何递归调用。我认为这是问题的一部分。 :)

标签: java binary-search-tree


【解决方案1】:

一些提示:

  • 我在insert 中看不到任何递归调用。如果没有适当的递归调用(基于值进入当前节点的左子树或右子树),您将如何遍历 BST?我确实看到了一些看起来像是会执行这些调用的注释掉的代码。为什么他们被注释掉了?
  • 您将返回新插入的节点,然后将其设置为root。这会将root 设置为每次都指向新节点。我认为这不是你想要的。
  • 如果您要尝试处理树为空的特殊情况,您只需检查root 是否为null,然后将新节点设置为此。
  • 真的没必要回ptr。由于您的 BST 维护对 root 的引用,因此您始终拥有对树根的引用。每次插入时,从root开始,然后递归遍历树,直到找到合适的位置插入新节点。如果您确实必须返回引用,那么您绝对不应该将 root 设置为该新节点!

这里有一些伪代码可以帮助你:

// Recursive function that inserts a value into a BST
function insert(node, value):

    //Handles the case where you have no nodes in the tree, so root is null
    if node is null:
        node = new Node(value)

    // If the value is lesser than the current node's value, we need to insert it
    // somewhere in the right subtree
    else if value < node.value:
        if node.right is null:
           // This node doesn't have a right child, so let's insert the new node here
           node.right = new Node(value)
        else:
           // This node has a right child, so let's go further into this subtree to
           // find the right place to insert the new node
           insert(node.right, value)

    // If the value is greater than the current node's value, we need to insert it
    // somewhere in the left subtree
    else if value > node.value:
        if node.left is null:
           // This node doesn't have a left child, so let's insert the new node here
           node.left = new Node(value)
        else:
           // This node has a left child, so let's go further into this subtree to 
           // find the right place to insert the new node
           insert(node.left, value)
    else:
        // A node with this value already exists so let's print out an erro
        error("Node with that value already exists")

end function

【讨论】:

  • 这不是真正的家庭作业,因为我没有要上交的作业;但是,如果我们的下一个项目需要它,我正在尝试变得更加熟悉...我已将其注释掉,因为它在比较中从“ptr = ptr.left”或“ptr.right”跳过>
  • @ChristopherDay 啊,好的。我将发布一些伪代码来帮助您并为您指明正确的方向!我不想剥夺你自己解决问题的乐趣:)
  • 感谢您愿意提供的任何帮助!我要更新我的 OP,因为取消注释会导致“无法访问的代码”错误。我将恢复到一些具有相同结果的旧代码。
  • @ChristopherDay 没问题;很高兴为您提供帮助!
  • 胜利是我的!!!尝试了几次,但我越来越熟练地使用调试器并了解它内部的情况 - 干杯。
猜你喜欢
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 2018-12-31
  • 2016-03-19
相关资源
最近更新 更多