views:

856

answers:

2

Just a simple binary tree and i want to find the the largest node.
example tree: t(t(t(nil,1,nil),2,t(nil,3,nil)),4,t(t(t(nil,8,nil),5,nil),6,t(nil,7,nil)))

int L(t,max) {
if(t=null) return max;
if(max<t.root) max = t.root;
LN(t,max);
RN(t,max);
return max;
}
L(tree,tree.root);

I just cant wrap my head around applying it to prolog. Here i display each node. Which i get, but i dont understand how to save the max value and keep it recursively.

tree(nil).
tree(t(L,Root,R)) :- 
    tree(L),
    tree(R), 
    write(Root).

edit: It checks all the leaf nodes, but ignores the t(nil,8,nil)

tree(nil,0).
tree(t(nil,Q,nil),Q) :- !.
tree(t(nil,Q,_),Q).
tree(t(_,Q,nil),Q).
tree(t(L,_,R),Max) :- 
    tree(L, LValue),
    tree(R, RValue), 
    max(LValue,RValue,Max).
+2  A: 

Is this another homework assignment?

In any case, I'll try to let you do the thinking since you seem to be learning Prolog. Not to mention the fact that I don't actually have Prolog running on my computer, so I couldn't be sure my suggested solution would actually work.

The fact that the 5 is the only node with only one subnode (i.e. the 8 it's ignoring) should tell you something. All the other nodes are either leaf nodes or have two subnodes.

What exactly is it that you think these two rules do?

tree(t(nil,Q,_),Q).
tree(t(_,Q,nil),Q).
mercator
Hey, i changed the way i was thinking about, i just traversed the tree and created a list, than i found the largest number from the list, and done. But i think that is the wrong approach here. I have a hard time thinking in terms of prolog/recursion i think.
chicken
actually thinking harder, i solved it without using a list :).
chicken
Excellent... It takes a while to get used to. I haven't used Prolog in years myself, so it's a nice refresher for me too. :) Wouldn't simply removing those two rules I mentioned from your existing code also have solved it? I may have to install Prolog now...
mercator
A: 

CSC326 chicken? :D

nope comp3007 buddy.
chicken
i really dont get what everyones problem is with asking for help, its not like im even providing the question or asking for the answer, im just asking for help, how is it any different it i ask another student or the prof?
chicken
Any CS student who's figured out stackoverflow.com is on the right track. So long as you're open about what you're looking for, I don't think there's any problem.
Rich