【问题标题】:BST node with no children not being deleted没有子节点的 BST 节点未被删除
【发布时间】:2018-11-18 11:26:55
【问题描述】:

我的 BST 在删除有子节点后不会删除没有子节点的节点。

删除功能:

private Node remove(Node current, Pair k) throws DictionaryException {
        if (current == null) {
            throw new DictionaryException("Key does not exist");
        }

        if (k.compareTo(current.data.getKey()) < 0) {
            current.left = remove(current.left, k);
        } else if (k.compareTo(current.data.getKey()) > 0) {
            current.right = remove(current.right, k);
        } else {
            if (current.left == null && current.right == null) {
                current = null;
            } else if (current.right == null) {
                current = current.left;
            } else if (current.left == null) {
                current = current.right;
            } else {
                Record smallest = smallest(current.right).data;
                current.data = smallest;
                remove(current.right, smallest.getKey());
            }
        }
        return current;
    }

主要:

public static void main(String[] args) {
    Pair key1 = new Pair("homework", "text");
    Record record1 = new Record(key1, "hello world");

    Pair key2 = new Pair("course", "text");
    Record record2 = new Record(key2, "world hello");

    Pair key3 = new Pair("class", "text");
    Record record3 = new Record(key3, "bean man");

    Pair key4 = new Pair("computer", "text");
    Record record4 = new Record(key4, "despacito");

    Pair key5 = new Pair("four", "text");
    Record record5 = new Record(key5, "zebras");

    OrderedDictionary od = new OrderedDictionary();

    try {
        od.put(record1);
        od.put(record2);
        od.put(record3);
        od.put(record4);
        od.put(record5);
    } catch (DictionaryException e) {
        System.out.println("exception in main - put");
    }

    try {
        od.remove(key2);
    } catch (DictionaryException e){
        System.out.println("exception in main - remove");
    }

    od.preOrder();

我希望od.preOrder(); 会返回“家庭作业四级计算机”。但相反,它返回:“作业四类计算机四”。出于某种原因,它没有删除“Course”的右孩子“四”,我不知道为什么。

【问题讨论】:

    标签: java binary-search-tree


    【解决方案1】:

    要删除根元素时有些棘手。您可以通过将root-right-child 设置为root-left-child 的最右边子元素的right-child 来实现,反之亦然,而不是修改根元素的值并删除右分支的最右边元素。

    【讨论】:

      【解决方案2】:

      想通了...只需将remove(Node current, Pair k) 中的remove(current.right, smallest.getKey()); 更改为current.right = remove(current.right, smallest.getKey());,以便它引用正确的节点

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 2014-05-26
        相关资源
        最近更新 更多