繁体   English   中英

二进制搜索树不删除节点

[英]Binary Search Tree not deleting Node

我创建了一个Binary Search Tree并尝试在添加特定节点后删除它们。 我可以成功delete大约5个Nodes但是当我尝试删除Node with id 109Node with id 109它只会忽略它,什么也不会发生。 我已经尝试了许多删除它的方法,但是它不起作用。

myBinaryTree.deleteNode(myBinaryTree.root, 109);

这是我的二叉树中的delete方法。

public Node deleteNode(Node root, int ID){

    if (root == null)  return root;
    if (ID < root.ID)
        root.leftChild = deleteNode(root.leftChild, ID);
    else if (ID > root.ID)
        root.rightChild = deleteNode(root.rightChild, ID);

    else
    {
        if (root.leftChild == null)
            return root.rightChild;
        else if (root.rightChild == null)
            return root.leftChild;

        root.ID = minValue(root.rightChild);
        root.rightChild = deleteNode(root.rightChild, root.ID);
    }

    return root;
}


int minValue(Node root)
{
    int minv = root.ID;
    while (root.leftChild != null)
    {
        minv = root.leftChild.ID;
        root = root.leftChild;
    }
    return minv;
}

和我的Node

public class Node {
    int ID;
    Dancer.Gender gender;
    int height;

    Node leftChild;
    Node rightChild;

    Node(int ID, Dancer.Gender gender, int height) {

        this.ID = ID;
        this.gender = gender;
        this.height = ID;

    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

}

ID按照预期的方式工作,这意味着deleteNode方法deleteNode获取正确的ID,只是不会删除它。

这是我要从中删除的树的图片:

在此处输入图片说明

如果需要有关如何添加节点等的更多信息,那么我也可以提供。 真是太奇怪了,直到我尝试删除ID = 109节点之前,这一切都可以正常工作。

您的代码看起来不错。

顺便说一句,您如何验证未删除该节点? 我只是检查了您的代码并打印了遍历顺序。 而且效果很好。

// This is java code.
void inorder(Node root){
    if (root ==null)return;
    inorder(root.leftChild);
    System.out.print(root.ID + "  ");
    inorder(root.rightChild);
}

// verify deletion by printing inorder traversal before and after
public static void main(String[] args) {
    // creating the tree
    Node root = new Node(60);
    root.leftChild = new Node(40);
    root.rightChild = new Node(109);
    root.leftChild.leftChild = new Node(20);
    root.leftChild.rightChild = new Node(49);

    inorder(root); // Printing before deleting
    System.out.println();
    myBinaryTree.root = deleteNode(myBinaryTree.root, 109); // delete the node and collect the new reference of the root.
    inorder(root); // Printing after tree
    System.out.println();
}

暂无
暂无

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

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