0

A binary tree of numbers is called a heap (or, it is said to satisfy the heap property) if, for every non-leaf node in the tree, the number stored at that node is less than or equal to the number stored at each of its children. For example, the following tree satisfies the heap property, because 3 ≤ 5, 5 ≤ 8 and 5 ≤ 7.

tree(empty,3,tree(tree(empty,8,empty),5,tree(empty,7,empty)))

On the other hand, the following tree does not satisfy the heap property, because 6 is not less than or equal to 5.

tree(tree(tree(empty,4,empty),
        3,tree(empty,5,empty)),6,tree(tree(empty,9,empty),7,empty))

Example :

?- is_heap(tree(tree(tree(empty,4,empty),
         3,tree(empty,5,empty)),6,tree(tree(empty,9,empty),7,empty))).
false.

?- is_heap(tree(empty,3,tree(tree(empty,8,empty),5,tree(empty,7,empty)))).
true 

Any help will be appriciated.

false
  • 10,264
  • 13
  • 101
  • 209
  • in most tree examples I have seen in books it is `tree(Value, Left, Right)` not `tree(Left, Value, Right)` but I guess this is not important. More important is that you make no effort to write any code at all only ask for someone to write your code even though the code that you need to write is quite trivial to write and probably you could write it as good as me or anyone else. I give you minus for this :-( sorry –  Apr 04 '17 at 12:44
  • here is idea: you look at value in each non-leaf node and then you check that both left and right child has less than that value and you do this recursively as long as you have `tree(L, V, R)` and not `empty`. Then if you succeed you get `true` otherwise you get `false`. –  Apr 04 '17 at 12:51
  • Possible duplicate of [Check if a tree is a min heap](http://stackoverflow.com/questions/43187131/check-if-a-tree-is-a-min-heap) –  Apr 04 '17 at 20:32

1 Answers1

1

You can start like this. Here tree is tree(Value, Left, Right) but you can change this easily. Then you start:

is_heap(empty).
is_heap(tree(X, L, R)) :-
    is_heap(L, X),
    is_heap(R, X).

Now you only need to write is_heap/2 and then you are ready. Something like:

is_heap(empty, ...).
is_heap(tree(X, L, R), X0) :-
    ...,
    is_heap(L, X),
    ....