Buenas, alguien me prodria corregir el siguiente codigo:
Es sobre Arboles balanceados por altura (AVL); El problema es cuando por ejemplo se ingresa el siguiente arbol:
50 13 40 el error bucle infinito se produce en el procedimiento Balancear(A:AVL). AYUDA!!!!
 
Procedure AgregarHijo(VAR A:AVL; X:Trotulo; var cod:integer);
Var
Balance:Integer;
Begin
if A<>nil then
  Begin
    if IgualRotulo(x, A^.info) {x=A^.info} then cod:=1 else
    If MenorRotulo(x, A^.info) {x<A^.info} then AgregarHijo(A^.HI, X, cod) else
                        AgregarHijo(A^.HD, x, cod);
                cod:=0;
    Balancear(A);
  end else
  Begin
    New(A); AsignarRotulo(x, A^.info); {A^.info:=X}
    A^.hi:=nil; A^.hd:=nil;
  end;
end;
{-----------------------------------------------------------------------------------}
Function Altura(A:AVL):Integer; {Simplemente saca la altura de un arbol, los arboles nulos tiene altura -1}
Var
ASI,ASD:integer;
Begin
  If A=nil then ALtura:=-1 else
  Begin
    ASI:=Altura(A^.HI)+1;
    ASD:=Altura(A^.HD)+1;
    If ASI<=ASD then Altura:=ASD else ALtura:=ASI;
  end;
end;
{-----------------------------------------------------------------------------------}
Procedure RotSimpleDerecha(var A:AVL);
var
q,temp:ptrAVL;
Begin
  if A<>nil then
  Begin
    Q:=A^.HI;
    Temp:=Q^.hd; 
    Q^.HD:=A;
    A^.HI:=temp;
                a:=Q;
  end;
end;
{-----------------------------------------------------------------------------------}
Procedure RotSimpleIzquierda(VAR A:AVL);
Var
q,temp:ptrAVL;
Begin
  If A<>nil then
  Begin
    Q:=A^.hd;
    temp:=Q^.HI;
    Q^.hI:=A;
    A^.hd:=temp;
                a:=q;
  end;
end;
{-----------------------------------------------------------------------------------}
Procedure Balancear(var A:AVL);
Var
Balance{,stack}:Integer;
Begin
        stack:=0;
  If A<>nil then
  Begin
    Balance:=Altura(A^.HI)-Altura(A^.HD);
    While (Balance=2) or (Balance=-2) {and (stack<=3)} do
    Begin
      If balance=2 then RotSimpleDerecha(A) else
                                                              RotSimpleIzquierda(A);
      Balance:=Altura(A^.HI)-Altura(A^.HD); {inc(stack);}
    end;
  end;
end;
{-----------------------------------------------------------------------------------}
 
 
Gracias, espero que me puedan ayudar...  
