我最近在通过删除树的根“节点”来销毁树时设法获得堆栈溢出,而节点析构函数与此类似:
Node::~Node(){
for(int i=0;i<m_childCount;i++)
delete m_child[i];
}
我想到的一个解决方案是使用自己的堆栈。所以以这种方式删除树:
std::stack< Node* > toDelete;
if(m_root)
toDelete.push(m_root);
while(toDelete.size()){
Node *node = toDelete.top();
toDelete.pop();
for(int i=0;i<node->GetChildCount();i++)
toDelete.push(node->Child(i));
delete node;
}
但是在那里 std::stack::push() 可能会抛出异常。是否可以编写无异常树销毁?如何?
编辑:
如果有人对这里感兴趣,这里是一个受 jpalecek 指出的算法启发的无异常非递归代码:
Node *current = m_root;
while(current){
if(current->IsLeaf()){
delete current;
return;
}
Node *leftMostBranch = current;// used to attach right subtrees
// delete all right childs
for(size_t i=1; i<current->GetChildCount(); i++){
while(!leftMostBranch->Child(0)->IsLeaf())
leftMostBranch = leftMostBranch->Child(0);
delete leftMostBranch->Child(0);
leftMostBranch->Child(0) = current->Child(i);
}
// delete this node and advance to the left child
Node *tmp = current;
current = current->Child(0);
delete tmp;
}
注意:Node::IsLeaf()
相当于Node::GetChildCount()!=0
.