% nacteni:
/* ['2.6_13.pl']. */

addleaf(nil,X,t(nil,X,nil)).
addleaf(t(Left,X,   Right),X ,t(Left ,X,   Right)).
addleaf(t(Left,Root,Right),X ,t(Left1,Root,Right))  :- Root>X,addleaf(Left, X, Left1).
addleaf(t(Left ,Root,Right),X,t(Left ,Root,Right1)) :- Root<X,addleaf(Right,X,Right1).

show(T) :- show2(T,0).
show2(nil,_).
show2(t(L,X,R),Indent) :- Ind2 is Indent+2,show2(R,Ind2),tab(Indent),
                          write(X),nl,show2(L,Ind2).

% demonstracni vypis

  % abychom se vyhli varovanim "Redefined static procedure ..."
:- dynamic
       start/0.
       
start:- 
    write('Binarni stromy'),nl,
    write('--------------'),nl, nl,
    write('Vysledek volani '),nl,
    write('addleaf(nil ,6,T),addleaf(T,8,T1), addleaf(T1,2,T2),'),nl, 
    write('addleaf(T2,4,T3), addleaf(T3,1,T4), show(T4) :'),nl,
    addleaf(nil ,6,T),addleaf(T,8,T1), addleaf(T1,2,T2), addleaf(T2,4,T3), addleaf(T3,1,T4),
    show(T4),

    write('Vysledek volani '),nl,
    write('addleaf(t(t(t(nil,1,nil),2, t( t( nil ,3, nil ),4, t( nil ,5, nil ))),'),nl,
    write(' 6, t( t( nil ,7, nil ),8, t( nil ,9, nil ))), 10, T5), show(T5) :'),nl,
    addleaf(t(t(t(nil,1,nil),2, t( t( nil ,3, nil ),4, t( nil ,5, nil ))), 6, t( t( nil ,7, nil ),8, t( nil ,9, nil ))), 10, T5),
    show(T5).

?-start.

:- retractall(write_all_X/3).
:- retractall(start/0).
