我正在构建一个 AVL 树。我有一种删除树中项目的方法,但出现错误。
这是我得到的运行时错误:
malloc: *** error for object 0x100100120: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
jim Abort trap
我的课看起来像这样:
struct Avlnode{
string data;
int balfact;
Avlnode *left;
Avlnode *right;
};
class Avltree{
public:
Avltree();
~Avltree( );
Avlnode* insert(string i, bool* j);
static Avlnode* buildtree ( Avlnode *root, string data, bool *h ) ;
void display( Avlnode *root );
Avlnode* deldata ( Avlnode* root, string data, bool *h );
static Avlnode* del ( Avlnode *node, Avlnode* root, bool *h );
static Avlnode* balright ( Avlnode *root, bool *h );
static Avlnode* balleft ( Avlnode* root, bool *h );
void setroot ( Avlnode *avl );
static void deltree ( Avlnode *root );
private:
Avlnode *root;
int items;
};
deldata 的定义如下:
Avlnode* Avltree::deldata ( Avlnode *root, string data, bool *h ){
Avlnode *node;
if ( root == NULL ){
//cout << "\nNo such data.";
return ( root );
}
else{
if ( data < root -> data ){
root -> left = deldata ( root -> left, data, h ) ;
if ( *h )
root = balright ( root, h ) ;
}
else{
if ( data > root -> data ){
root -> right = deldata ( root -> right, data, h ) ;
if ( *h )
root = balleft ( root, h );
}
else{
node = root;
if ( node -> right == NULL ){
root = node -> left ;
*h = true ;
delete ( node ) ;
}
else{
if ( node -> left == NULL ){
root = node -> right ;
*h = true ;
delete ( node ) ;
}
else{
node -> right = del ( node -> right, node, h ) ;
if ( *h )
root = balleft ( root, h ) ;
}
}
}
}
}
return ( root ) ;
}
Avlnode* Avltree :: del ( Avlnode *succ, Avlnode *node, bool *h ){
Avlnode *temp = succ ;
if ( succ -> left != NULL ){
succ -> left = del ( succ -> left, node, h ) ;
if ( *h )
succ = balright ( succ, h ) ;
}
else{
temp = succ ;
node -> data = succ -> data ;
succ = succ -> right ;
delete ( temp ) ;
*h = true ;
}
return ( succ ) ;
}
为什么我会收到此错误?