私は最近、ルート 'ノード' を削除してツリーを破棄するときにスタック オーバーフローを取得することができましたが、ノード デストラクタは次のようになります。
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
です。