【问题标题】:How does the following Binary Search Tree node removal method work?以下二叉搜索树节点删除方法如何工作?
【发布时间】:2021-04-07 16:09:37
【问题描述】:

疑问在于最终删除步骤(在 final else 语句中)以及如何重新分配父节点对子节点的引用。 代码来自 Mark Allen Weiss 的C++ 中的数据结构和算法分析一书。 完整代码参考:https://users.cis.fiu.edu/~weiss/dsaa_c++3/code/BinarySearchTree.h

据我了解程序,节点指针 t 指向要删除的节点。
然后将该指针复制到节点指针 oldNode,然后 t 指向一个子节点(如果有)(在这种情况下,由于 findMin 是右子节点)。
oldNode 指向的节点随后被删除。
但是父节点指针(oldNode所指向的节点的父节点的parent->leftparent->right)是如何分配给指向t所指向的子节点?
t 的条件赋值是否会发生这种情况?

方法如下:

 void remove( const Comparable & x, BinaryNode * & t )
    {
        if( t == NULL )
            return;   // Item not found; do nothing
        if( x < t->element )
            remove( x, t->left );
        else if( t->element < x )
            remove( x, t->right );
        else if( t->left != NULL && t->right != NULL ) // Two children
        {
            t->element = findMin( t->right )->element;
            remove( t->element, t->right );
        }
        else
        {
            BinaryNode *oldNode = t;
            t = ( t->left != NULL ) ? t->left : t->right;
            delete oldNode;
        }
    }

//findMin method used in the above routine

BinaryNode * findMin( BinaryNode *t ) const
    {
        if( t == NULL )
            return NULL;
        if( t->left == NULL )
            return t;
        return findMin( t->left );
    }



 

【问题讨论】:

  • 提示:在 C++ 中使用 nullptr 优先于 C 的无类型 NULL
  • 因为引用传递。

标签: c++ binary-tree


【解决方案1】:

remove 函数的签名中,BinaryNode * &amp; t 是对BinaryNode 类型指针的引用。也就是说,它是一个父节点左/右节点指针的引用。

我为你做了一个简单的图表,因为“一张图片胜过千言万语”。

所以基本上,它首先将引用所引用的实际指针(橙色箭头)保存到oldNode,然后将引用变量(红点)设置为指向下一个子项的指针(绿色箭头),跳过oldNode,最后删除oldNode

【讨论】:

  • 感谢您的解释,现在我可以看到发生了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
相关资源
最近更新 更多