我正在尝试为指针堆实现insert函数。每个节点(“BinaryNode”)存储一个int和一个字符串。我的插入功能基于解释here。但是,当我使用此函数创建二叉树时,它似乎在进入分支时出现内存泄漏
else {
BinaryNode *curr;//potential problem
...}
例如,当我插入1,2,3,4,5(按此顺序)时,我希望树看起来像树here。下面是我的插入功能。
void MyTree::insert (int x ,string s) {
++size;
BinaryNode *pointer = new BinaryNode(s,x);
if (root == NULL) {
root = pointer;
tail = root;
return;
}
else if (tail == root) {
tail = pointer;
tail->parent = root;
root->lchild = tail;
}
else if (tail == tail->parent->lchild) {
tail->parent->rchild = pointer;
pointer->parent = tail->parent;
tail = pointer;
}
else {
BinaryNode *curr;//potential problem
for (curr = tail; curr->parent != NULL && curr == curr->parent->rchild; curr = curr->parent) {
continue;
if (curr == root)
break;
}
if (curr != root) {
curr = curr->parent->rchild;
}
while (curr->lchild != NULL) {
curr = curr->lchild;
}
cout << "curr: " << curr->getInt();
curr->lchild = pointer;
pointer->parent = curr;
tail = pointer;
}
return;
}
当我尝试存储BinaryNodes的向量时,我意识到了这个问题。当我尝试将包含3的节点作为int推回时,我收到以下错误:
*** Error in `./a.out': free(): invalid pointer: 0x00000000021cb010 ***
======= Backtrace: =========
...
回顾一下,调用insert函数不会给我任何错误,但是尝试将包含3的节点存储在向量中会产生上述错误。
如果我的插入函数看起来很好,那么我会知道看另一个函数。任何见解都表示赞赏!