AVL Binary Heap(Balanace test)

笑着哭i 提交于 2019-12-02 06:40:32

Each branch of an AVL tree is first of all supposed to be an AVL tree itself. Only if that is true should you compare the heights.

The tree in chac's answer is obviously unbalanced, but your code deems it OK. It is not.

Then, the typos. If you use short names, less likely to happen.

avl_height(b(L,R),H) :-
  avl_height(L,h(H1)), 
  avl_height(R,h(H2)), 
  abs(H1-H2) =< 1, !,
  H3 is 1 + max(H1,H2), H=h(H3).

avl_height(b(_,_),not).

avl_height(l(_),h(1)).

the code seems fairly ok, maybe indenting the data and using the same functors as found in the comment can help:

t :- avl(b(l(1),
           b(l(2),
             b(l(3),
               b(l(4),
                 l(5)
                )
              )
            )
          ),
         b(l(6),
            b(l(7),
              b(l(8),
                b(l(9),
                  l(10)
                 )
             )
          )
        )
    ).

avl(LeftBranch,RightBranch) :-
  height(LeftBranch,H1),
  height(RightBranch,H2),
  abs(H1-H2) =< 1.

height(l(_),1).
height(b(LeftBranch,RightBranch),H) :-
  height(LeftBranch,H1),
  height(RightBranch,H2),
  H is max(H1,H2)+1.

Formatting by hand it's tedious. If you use SWI-Prolog, the IDE will do for you, just place a newline after each comma.

test:

?- t.
true.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!