How to find the depth of a binary tree using Prolo

2019-08-01 03:58发布

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.

标签: prolog
2条回答
Summer. ? 凉城
2楼-- · 2019-08-01 04:40

Easy as pie: the depth of nil is 0:

depth(nil,0).

For the tree case, recursively call depth/2 on both branches and max them:

depth(Left,DLeft),
depth(Right,DRight),
D is max(DLeft, DRight) + 1.
查看更多
倾城 Initia
3楼-- · 2019-08-01 04:43
% I added Root \= nil, simulating a null node and it works

depth_tree(nil, 0).

depth_tree(node(Root, Left, Right), Depth):- 

      Root\= nil, 

      depth_tree(Left, DepthLeft),

      depth_tree(Right, DepthRight),

      Depth is max(DepthLeft, DepthRight) + 1.
查看更多
登录 后发表回答