私はAVLツリーの実装に取り組んでおり、高さの再計算機能に問題があります。それを呼び出すと、ツリーのルートと値が 1 の変数を渡します。ステップ実行したところ、while ループに到達すると期待どおりに実行されますが、その後は 1 に戻ります。それを見て、私が間違っていることを確認してください。必要に応じてさらにコードを投稿しますが、関数だけで十分な情報が得られると思います。ありがとう
void BinaryTree::recalculate(Node *leaf, int count)
{
if(leaf == NULL)//if we are at the root
{
return;//exit the function
}
if((leaf->getLeft() != NULL))//if we are not at the end of the subtree
{
recalculate(leaf->getLeft(), count);//advance to the next node and re-enter the function
}
if(leaf->getRight() != NULL)//if we are not at the end of the right subtree
{
recalculate(leaf->getRight(), count);//advance to the next node and re-enter the program
}
else
{
while(leaf->getParent() != NULL)//calculate each subtree until we are at the root
{
leaf = leaf->getParent();//get the parent node
count++;//increment the height
if(leaf->getLeft() != NULL)//if there is an item in the left
{
leaf->getLeft()->setHeight(count-1);//sets the hight of the left child
}
if(leaf->getRight() != NULL)//if there is an item in the right
{
leaf->getRight()->setHeight(count -1);//sets the height of the right child
}
}
return;//exit the function
}
}