我正在研究 AVL 树的实现,并且我的重新计算高度函数有问题。当我调用它时,我传入了树的根和一个值为 1 的变量。我单步执行了它,发现一旦它进入 while 循环,它就会按预期执行,但之后它会返回一个。你能看看它,看看我做错了什么。如果需要,我会发布更多代码,但我认为该功能将为您提供足够的信息。谢谢
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
}
}