在BST中删除节点

时间:2016-07-09 03:15:07

标签: java binary-search-tree

我正在研究一种从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;

}

1 个答案:

答案 0 :(得分: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