Search code examples
arraystreeprologinorder

Prolog: Convert tree to order list and check if the list is sorted


Now I want to check if a tree is a search tree, so that the In-Order traverse is an ascending array. (So if the tree is sorted) - it almost works. But I can't find my mistake now, so unfortunately I have a thinking block. First a list of the tree is created, then it passes to the isSorted method, which then returns the error.

% List Methode
append([], Ys, Ys).
append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).

% inorder Traversel  - work coorect
inorder(nil, []).

inorder(tree(X, Left, Right), R) :-
   inorder(Left,R1),
   inorder(Right,R2),
   append(R1,[X|R2],R).

% contains - work coorect
contains(tree(_,L,_), X) :- contains(L,X).
contains(tree(X,_,_), X).
contains(tree(_,_,R), X) :- contains(R,X).

% isSorted
% TODO:
% Convert tree to list
% Check list whether list is correct.

% Der Fehler liegt irgendwo hier.

isSorted([]).
isSorted([_]).
isSorted(tree(X,Left,Right)) :- inorder(tree(X,Left,Right),X), isSorted(X).
isSorted([X,Y|T]) :- X=< Y, isSorted([Y|T]).




% ?-inorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X). -> work
% isSorted(inorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X)). -> doesn't work

Solution

  • Try with this isSorted predicate:

    isSorted([]).
    isSorted([_]).
    
    isSorted([X|[Y|_]]) :- 
        X=< Y, 
        isSorted([Y|_]).
    
    isSorted(tree(X,Left,Right)) :- 
        inorder(tree(X,Left,Right),Z), 
        isSorted(Z).
    

    But your query must be:

    ?- isSorted(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil))).
    

    Remember that Prolog is not Functional Programming. You can't expect p(q(X,Z)) works as a Function composition, if you want something like that you need to make:

    r(X):- 
        q(X,Z),
        p(Z).
    


    One more thing: you can't overwrite the value of a variable. So, when you write

    " inorder(tree(X,Left,Right),X)" you are not overwriting the value of X. You are asking that a tree with root node X is such that the inorder of that tree is X.