c - balance() 函数无法正常工作
问题描述
在 bf() 函数中,我尝试将平衡因子分配给我的AVL 树的每个节点。当我通过传递树从 main() 函数调用函数时,第一次迭代工作得很好。但是在第一次递归之后, balance() 函数没有响应,代码也没有继续进行。我已经打印了“g”和“m”字母,以了解代码的工作位置。 当我从主函数调用时,'g'只打印一次,但'm'甚至没有打印一次。
int balance(struct node *tree)
{
int lh,rh;
if(tree==NULL)
return 0;
else
{
lh=balance(tree->left);
rh=balance(tree->right);
return (lh+1)-(rh+1);
}
}
void bf(struct node *tree)
{
tree->bfactor=balance(tree); //not proceeding after this step after first recursion.
printf("g");
bf(tree->left);
printf("m");
bf(tree->right);
}
解决方案
bf() 函数仅在树不等于 NULL 时才起作用。只需将此条件添加到 bf() 函数即可使其正常工作。
void bf(struct node *tree)
{
if(tree!=NULL)
{
tree->bfactor=balance(tree);
bf(tree->left);
bf(tree->right);
}
}
推荐阅读
- javascript - 如何在 UseEffect 中渲染页面/组件?
- android - Xamarin Forms 使用 CrossGeolocator 获取前台服务位置更新
- python - 雷工死亡的可能原因有哪些?
- prometheus - 编排器 API 的指标命名约定
- javascript - 将对象复制到 jQuery 的另一个对象
- npm - 重新发布后,npm 包未显示在注册表中
- python - Python to sharepoint Forbidden for URL
- mongodb - MongoDB docker副本集连接错误“找不到主机”
- reactjs - 使用不返回任何内容的脚本反应组件
- mysql - SQL比较同一表中的两行并创建新列