首页 > 解决方案 > 为什么我的检查 BST 树是否 AVL 错误的代码?

问题描述

嗨,我编写了这段代码来检查给定的 BST 是否为 AVL,在我看来它可以工作,但在测试中却不行。该结构是一个经典的 BST,有一个整数,左右。

bool AbsoluteDifference(int a, int b)
{
return ((a-b) <= 1)) ||(b-a) <= 1)); 
} 

 void aux_avl (BST b , int &l_var, bool &isAVL)
{
if (b == NULL)
  l_var--;  
  //In consecuence of not asking if the left or right is NULL or not
  //when I make the recursive call, if it is I have to decrease the value
else if (isAVL == true)//I don't want to keep checking if I already know that it's not AVL

{

   int l_left = l_var + 1;
   aux_avl(b->left,l_left,isAVL);

   int l_right = l_var +1;
   aux_avl(b->right, l_right,isAVL); 

   isAVL = AbsoluteDifference(l_left,l_right);

   lvar = max(l_left,l_right);
}
}

bool is_AVL(BST b)
{
   if (b == NULL)
      return true;
   else
  {
     int l_var =0;
     bool isAVL = true;
     auxavl(b,l_var,isAVL);

     return isAVL;
  }
}

标签: cbinary-search-tree

解决方案


推荐阅读