我正在学习 Prolog,并试图找到一个深度二叉树使用 Prolog。
我代表一棵树是这样的:
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.
我想要一个深度谓词,如果 N 是树 T 的深度,则深度(T,N)将为真。
我假设当 T 不是变量但 N 可以是变量时我将使用深度谓词。例子:
?- 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.
我不知道如何使 N 成为两棵子树之间的最大值。
谢谢你的帮助。
解决方案:
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.