【发布时间】:2015-07-05 22:03:25
【问题描述】:
我只是为了学习而尝试实现 AVL 树。我设法进行了插入,但我被困在删除中。我在删除叶节点时遇到问题(单子情况很好)。问题是当我删除节点时,它不会从 BST 中删除,相反,它的值只是变成 0,所以当节点被删除时,树永远不会不平衡。我基本上在做的是,如果我遇到一个没有孩子的节点,我只是释放它。这是函数的代码(没有重新平衡部分):
node_t *Delete ( node_t *root, int num ){
if ( !root ){
printf ("Not Found\n");
return root;
}
//=======Search for the Element=============
if ( num > root->data )
Delete ( root->right , num );
else if ( num < root->data )
Delete ( root->left , num );
//======Delete element==============
else if ( num == root->data ){
if ( root->right && root->left ){ //two child case
node_t *auxP = root->right;
while ( auxP->left ) //finding the successor
auxP=auxP->left;
root->data = auxP->data;
root->right = Delete ( root->right, auxP->data );
}
else{ //one or no child
if ( !root->right && !root->left ){ // no childs
free(root);
}
else{ //one child
node_t *auxP = ( root->right ? root->right : root->left );
*root=*auxP;
free(auxP);
}
}
}
return root;
}
如果我有一棵这样的树:
10
/ \
5 15
/ \ \
2 6 17
我尝试删除6,就这样结束了
10
/ \
5 15
/ \ \
2 0 17
这可能是一个明显的错误,但我找不到。任何关于它为什么不起作用的解释将不胜感激。
【问题讨论】:
-
请通过这个了解删除的工作原理:geeksquiz.com/binary-search-tree-set-2-delete
标签: c binary-search-tree