【发布时间】: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->left或parent->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