A binary tree can be defined in terms of 2 predicates:
emptyBT
, the empty binary tree.BTTree(N,T1,T2)
that is true ifN
is the root of a binary tree with left subtreeT1
and right subtreeT2
, where all the items inT1
are less than or equal toN
and all the items inT2
are greater thanN
.
Write a Prolog program that implements the following predicates:
insert(I,T1,T2)
is true ifT2
is the binary tree resulting from I being inserted into binary treeT1
.preorder(T,L)
is true ifL
is a list of nodes generated by a preorder traversal of the binary treeT
.inorder(T,L)
is true ifL
is a list of nodes generated by a inorder traversal of the binary treeT
.postorder(T,L)
is true ifL
is a list of nodes generated by a postorder traversal of the binary treeT
.search(T,I)
is true ifI
is contained in the binary treeT
.height(T,H)
is true ifH
is the height of the binary treeT
. An empty tree has height0
and a tree with one item has height1
.
Here's my code so far: I have no idea if its right, any help or pointers would be greatly appreciated!
isempty(nil) :- !.
isempty(tree(nil,nil,nil)).
bTTree(tree(_,nil,nil)).
bTTree(tree(N,Left,nil)) :- Left@=<N.
bTTree(tree(N,nil,Right)) :- N@<Right.
bTTree(tree(_,Left,Right)) :- bTTree(Left), bTTree(Right).
bTTree(tree(N,Left,Right)) :- Left@=<N, N@<Right.
%traversals.
%preorder -- N,Left,Right
preorder(t,L) :- bTTree(t),
bTTree(t(N,Left,Right)),
append(N,[Left|Right],L).
preorder(t,L) :- bTTree(t(_,Left,_),
preorder(Left,L).
preorder(t,L) :- bTTree(t(_,_,Right),
preorder(Right,L).
%inorder -- Left,N,Right.
inorder(t,L) :- bTTree(t),
bTTree(t(N,Left,Right)),
append(Left,[N|Right],L).
inorder(t,L) :- bTTree(t(N,_,_)), inorder(N,L).
inorder(t,L) :- bTTree(t(_,_,Right)), inorder(Right,L).
%postorder -- Left,Right,N
postorder(t,L) :- bTTree(t),
bTTree(t(N,Left,Right)),
append(Left,[Right|N],L).
postorder(t,L) :- bTTree(t(_,_,Right)),
inorder(Right,L).
postorder(t,L) :- bTTree(t(N,_,_)),
append(_,[_|N],L).
search(t,I) :- bTTree(t(I,_,_)). %searches each node for I
search(t,I) :- bTTree(t(_,I,_)).
search(t,I) :- bTTree(t(_,_,I)).
search(t,I) :- bTTree(t(_,N,_)), search(N,I).%recursive method to search left branch for I
search(t,I) :- bTTree(t(_,_,N)), search(N,I).%recursive " " " right branch for I
height(t,H) :- bTTree(t(nil,nil,nil)), H is 0. %height of empty tree is 0
height(t,H) :- bTTree(t(_,nil,nil)), H is 1. %height of single node Btree is 1
height(t,H) :-
bTTree(t(_,Left,Right)), %otherwise height of bTree is the max
height(Left, H1), %height of left or right branch plus 1
height(Right, H2),
H is max(H1,H2) + 1.
insert(I,t1,t2) :-
bTTree(t1(X,L,_)),
bTTree(t2(X,L,I)).
insert(I,t1,t2) :-
bTTree(t1(nil,nil,nil)),
bTTree(t2(I,nil,nil)).
insert(I,t1,t2) :-
bTTree(t1(X,L,_)),
bTTree(t2(X,L,I)).