首页 > 解决方案 > 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);
      }

标签: cdata-structuresbinary-search-treeavl-tree

解决方案


bf() 函数仅在树不等于 NULL 时才起作用。只需将此条件添加到 bf() 函数即可使其正常工作。

void bf(struct node *tree)
  {  
       if(tree!=NULL)
       {
           tree->bfactor=balance(tree);
           bf(tree->left);
           bf(tree->right);
       }
  }

推荐阅读