[英]non recursive destructor for binary search tree by implementing stack
这段代码有运行时错误,我在确定问题所在时遇到了问题。 stack类具有基本的堆栈操作(pop push top),用于保存遍历的位置。
parityBST::~parityBST()
{
if (root == NULL)
{
return;
}
else
{
//postOrder non recursive traversal for destructor
stack* s1 = new stack();
s1->push(root);
binaryNode* nodePtr= root;
while (!s1->isEmpty())
{
//RUNTIME ERROR HERE (after several iterations)
if (nodePtr->left)
{
s1->push(nodePtr->left);
nodePtr = nodePtr->left;
} else if (nodePtr->right)
{
s1->push(nodePtr->right);
nodePtr = nodePtr->right;
} else
{
delete nodePtr;
s1->pop();
nodePtr = s1->getTop();
}
}
}
}
您正在(nodePtr的父级)->左侧delete
nodePtr,但没有将其更改为null,因此您将再次进入。
尝试添加以下内容:
s1->pop();
binaryNode* parent = s1->getTop()
if (parent->left==nodePtr)
parent->left = NULL;
else
parent->right = NULL;
delete nodePtr;
nodePtr = parent;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.