gpt4 book ai didi

prolog - 如何使用 Prolog 查找二叉树的深度

转载 作者:行者123 更新时间:2023-12-02 01:20:50 24 4
gpt4 key购买 nike

我正在学习 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 成为 2 个子树之间的最大值。

感谢您的帮助。

解决方案:

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.

最佳答案

简单易行:nil 的深度为 0:

depth(nil,0).

对于情况,在两个分支上递归调用深度/2max它们:

depth(Left,DLeft),
depth(Right,DRight),
D is max(DLeft, DRight) + 1.

关于prolog - 如何使用 Prolog 查找二叉树的深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4767868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com