【问题标题】:Deleting Node in BST在 BST 中删除节点
【发布时间】:2016-11-11 16:30:10
【问题描述】:

我正在研究一种从 BST 中删除节点的方法。在相同的方法中,我递归地搜索要删除的节点以及保存该节点的父节点。但是,唯一的问题是我不确定在case2中如何使根节点等于父节点(因为删除发生在父节点中)。

public Node delete(Node root, int data) 
{

    // base case - if tree is empty
    if (root == null)
        return root;

    // find the node to be deleted and keep track of parent 
    if (data < root.data)
    {
        parent = root;
        System.out.println("parent node: " + parent.data);
        root.left = delete(root.left, data);
    }
    else if (data > root.data) 
    {
        parent = root;
        System.out.println("parent node: " + parent.data);
        root.right = delete(root.right, data);


    // delete node
    }
    else 
    {
        // case 1: deletion node has no subtrees
        if (root.left == null && root.right == null)
        {
            System.out.println(data + " successfully deleted from tree (case1)");
            root = null;
        }

        // case 2: deletion node has only one subtree
        else if (root.left != null && root.right == null)
        {
            Node temp = root.left;
            if(parent.left.data == root.left.data)
            {
                parent.left = null;
                System.out.println(data + " successfully deleted from tree (case2)");
                parent.left = temp;
                root = parent; // parent was sent when searching for the node  

            } 
            else if(parent.right.data == root.data) 
            {
                parent.right = null;
                System.out.println(data + " successfully deleted from tree (case2)");
                parent.left = temp;
                root = parent; // parent was sent when searching for the node  
            }

        } 
        else if (root.left == null && root.right != null) 
        {
            // same logic 
        }
    }

    return root;

}

【问题讨论】:

    标签: java binary-search-tree


    【解决方案1】:

    你应该添加另一个函数来调用你的删除函数

        class BST{
            private Node root=null;
    
            private Node parent=null;// just for use by the deletion function
            public void delete(int data){
                Node dummy_node=new Node(0);//can be initialized to anything.
                dummy_node.setLeft(root); //right is null;
                parent=dummy_node;
                root=your_delete(this.root,data);
                dymmy_node=null;
            }
            public Node your_delete(Node root, int data) {
                //your code here
            }
        }
    

    这可行,但有更好的删除方法。这里:http://www.algolist.net/Data_structures/Binary_search_tree/Removal

    【讨论】:

    • 感谢分享。我去看看链接!
    猜你喜欢
    • 2021-04-06
    • 1970-01-01
    • 2021-05-24
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多