简体   繁体   English

Java二进制搜索树-不正确的插入方法

[英]Java binary search tree - incorrectly working insert method

I've a binary search tree homework in Java where I was given complete Tree and Node classes and a SearchTree class in which I'm to complete the search and insert methods. 我在Java中有一个二进制搜索树家庭作业,在其中给了我完整的Tree和Node类,以及一个SearchTree类,在其中完成搜索和插入方法。 The search is supposed to return the value of the node corresponding the searched key. 该搜索应该返回与搜索到的键相对应的节点的值。

Here is the Tree class and here the Node class. 是Tree类, 这里是Node类。 My search and insert methods are below. 我的搜索和插入方法如下。

It seems I'm getting close, but test insert of key 0 and value 2 into Tree[Node[0,1,null,null]] results in Tree[Node[0,1,null,null] rather than the correct Tree[Node[0,2,null,null]]. 似乎我接近了,但是将键0和值2测试插入Tree [Node [0,1,null,null]]会导致Tree [Node [0,1,null,null],而不是正确的Tree [Node [0,2,null,null]]。 What am I not understanding here? 我在这里不明白什么?

public static Object search(Tree tree, int key) {
    Node x = tree.getRoot();
    while (x != null) {
        if (key == x.getKey()) {
            return x.getValue();
        }
        if (key < x.getKey()) {
            x = x.getLeft();
        } else {
            x = x.getRight();
        }            
    }
    return null;
}

public static void insert(Tree tree, int key, Object value) {
    if (tree.getRoot() == null) {
        tree.setRoot(new Node(key, value));
    }
    Node juuri = tree.getRoot();
    while (juuri != null) {
        if (key == juuri.getKey()) {
            return;
        } else if (key < juuri.getKey()) {
            if (juuri.getLeft() == null) {
                juuri.setLeft(new Node(key, value));
                return;
            } else {
                juuri = juuri.getLeft();
            }
        } else {
            if (juuri.getRight() == null) {
                juuri.setRight(new Node(key, value));
                return;
            } else {
                juuri = juuri.getRight();
            }
        }
    }
}

Well the issue I am seeing is that key values in your tree are unique. 好吧,我看到的问题是树中的键值是唯一的。 In this if statement you leave your insert method without adding a node if you see that the key is already in the tree. 在此if语句中,如果看到密钥已经在树中,则无需添加节点即可保留insert方法。

 if (key == juuri.getKey()) { 
      return;
 }

In your example (if I understand it right) 0 is already in the tree so nothing changes when inserting 0 again. 在您的示例中(如果我理解正确的话)树中已经有0,因此再次插入0时没有任何变化。 Based on your example, I am assuming you want to do an update on a node if the key is the same. 根据您的示例,假设密钥相同,则假设您要在节点上进行更新。 So this code would do it. 因此,这段代码可以做到。

if (key == juuri.getKey()) {
     juuri.setValue(value);
     return;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM