在java中使用String作为BST键

时间:2018-04-01 22:15:55

标签: java binary-search-tree

我有一个存储对象的二叉搜索树。我可以使用String值是一个键,它只存储第一个键,并且只搜索第一个值,所有其他键找到返回null

第一个值是A

这是我的代码:帮助!

  public void addNode(String key, String name) {
    // Create a new Node and initialize it
    Node newNode = new Node(key, name);
    // If there is no root this becomes root
    if (root == null) {
        root = newNode;
    } else {
        // Set root as the Node we will start
        // with as we traverse the tree
        Node focusNode = root;
        // Future parent for our new Node
        Node parent;
        while (true) {
            parent = focusNode;
            if (key.compareTo(focusNode.name) <= 0) {
                // Switch focus to the left child
                focusNode = focusNode.leftChild;
                // If the left child has no children
                if (focusNode == null) {
                    // then place the new node on the left of it
                    parent.leftChild = newNode;
                    return; // All Done
                }
            } else if(key.compareTo(focusNode.name) >= 0){ // If we get here put the node on the right
                focusNode = focusNode.rightChild;
                // If the right child has no children
                if (focusNode == null) {
                    // then place the new node on the right of it
                    parent.rightChild = newNode;
                    return; // All Done
                }
            }
        }
    }

}

enter image description here

1 个答案:

答案 0 :(得分:1)

从我看到的问题是,您比较键值(在您的情况下为name)。例如,而不是:

 if (key.compareTo(focusNode.name) <= 0) {...

尝试:

if (key.compareTo(focusNode.key) <= 0) {...

另外,另一个问题是你永远不会处理两个键相等的情况,而是你继续前进到左边的孩子。您可能希望在此时执行其他操作,我猜测更新name并从方法返回。