I am learning Prolog and am trying to find the depth of a binary tree using Prolog. I represent a tree like this:
nil is a tree.
tree(1,nil,nil) this is a leaf.
tree(1,tree(1,nil,nil),nil) this is a tree with root 1 and has a left leaf 1.
I want a depth predicate that depth(T, N) that will be true if N is the depth of the tree T. I assume that I'll use the depth predicate when T isn't a variable but N can be a variable. Examples:
?- depth(nil,N).
N = 0.
?- depth(tree(1,tree(2,nil,tree(3,nil,nil)),tree(5,tree(6,nil,nil),nil)),N).
N = 3.
?- depth(tree(1,nil,tree(2,nil,nil)),N).
N = 2.
I am not sure how do that N will be the maximum between the 2 subtrees.
Thanks for any help.
Solution:
depth(nil,0).
depth(tree(_,nil,nil),1).
depth(tree(_,Left,Right), D) :-
depth(Left,DLeft),
depth(Right,DRight),
D is max(DLeft, DRight) + 1.
Easy as pie: the depth of
nil
is 0:For the
tree
case, recursively calldepth/2
on both branches andmax
them: