开发者

Erase function in Binary Search Tree

Can someone tell me what the following lines do

else if ( obj < retrieve() ) 
{
    return ( left() == 0 ) ? 0 : left()->erase( obj, left_tree );
} 
else 
{
    return ( right() == 0 ) ? 0 : right()->erase( obj, right_tree );
}

in the code block below:

    template <typename Comp>
    int Binary_search_node<Comp>::erase( Comp const &obj, Binary_search_node<Comp> *&ptr_to_this) 
{
    if ( obj == retrieve() ) {
        if ( leaf() ) { // leaf node
            ptr_to_this= 0;
            delete this;
        } 
        else if ( left() != 0 && right() != 0 ) { // full node
            element= right()->front();
            right()->erase( retrieve(), right_tree );
        } 
        else { // only one child
            ptr_to_this= ( left() != 0 ) ? left() : right();
            delete this;
        }
        return 1;
    } 
    else if ( obj < retrieve() ) {
        return ( left() == 0 ) ? 0 : left()->erase( obj, left_tree );} 
    else {
        return ( right() == 0 ) ? 0 : right()->erase( obj, right_tree );}
}

Extra Information:

1)

front() -- finds the minimum objects

Implementation:

template <typename Comp>
Comp Binary_search_node<Comp>::front() const 
{
    return( left() == 0 ) ?retrieve() :left()->front();
}

2)

left()  -- returns pointer to left subtree

3)

right() -- returns pointer to right subtree

4)

*ptr_to_this points to current object (same location as what *this points to)


I have an idea of what the lines do, but I am not 100% sure thus I wanted to confirm. Please note that this erase(开发者_运维知识库) function is for a binary search tree. Thanks!


Those lines are simply performing the search for the item you want to delete. In english it would read:

  • If the value to delete is less than the current value, then try to go left.
  • If the value to delete is greater than the current value, then try to go right.
  • If the node you are trying to go to does not exist, then return 0.


erase appears to be implemented recursively. At each stage, we test whether the object to erase is equal to the current object, or whether we need to go down into the left or right child.

If the child that we want to go into does not exist (left() == 0 or right() == 0), then we cannot erase the object (because it's not in the tree), so we return 0. Otherwise, we recurse into the child function, and return whatever it returns.


Your code searches the binary tree (and assumes its elements are sorted) for obj, and if it recursively finds it, deletes it and returns 1. If it doesn't find it, it will return 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜