用prolog检查结构是否为二叉树
使用结构:用prolog检查结构是否为二叉树,prolog,Prolog,使用结构: tree(tip). tree(bin(L,_,R)) :- tree(L), tree(R). 如何确定一棵树是否是一棵二叉树,左边的每个节点都比右边的每个节点小 到目前为止,我得到的是: bst(tip). bst(tip, _, _). bst(bin(bin(L, Ln, R), N, tip)):- N > Ln -> bst(bin(L, Ln, R)). bst(bin(bin(L, Ln, R), N, bin(L, Rn, R))):- ( N
tree(tip).
tree(bin(L,_,R)) :- tree(L), tree(R).
如何确定一棵树是否是一棵二叉树,左边的每个节点都比右边的每个节点小
到目前为止,我得到的是:
bst(tip).
bst(tip, _, _).
bst(bin(bin(L, Ln, R), N, tip)):- N > Ln -> bst(bin(L, Ln, R)).
bst(bin(bin(L, Ln, R), N, bin(L, Rn, R))):- (
N > Ln -> bst(bin(L, Ln, R)); false,
N < Rn -> bst(bin(L, Rn, R)); false
).
bst(提示)。
bst(提示,u,u)。
bst(bin(bin(L,Ln,R),N,tip)):-N>Ln->bst(bin(L,Ln,R))。
英国标准时间(bin(bin(L,Ln,R),N,bin(L,Rn,R)):-(
N>Ln->bst(bin(L,Ln,R));false,
Nbst(bin(L,Rn,R));假
).
我觉得你把这件事弄得太复杂了。我们可以在这里定义一个谓词来检查带有null
值的区间,以检查(非)有界区间。例如:
check(null, X) :-
!.
check(X, null) :-
!.
check(X, Y) :-
X < Y.
现在,我们可以实现bst/3
谓词,其中对于每个bin/3
复合项,我们检查值是否在范围内,然后递归地使用值作为新边界进行检查:
bst(tip, _, _).
bst(bin(L, V1, R), V0, V2) :-
check(V0, V1),
check(V1, V2),
bst(L, V0, V1),
bst(R, V1, V2).
我觉得你把事情弄得太复杂了。我们可以在这里定义一个谓词来检查带有
null
值的区间,以检查(非)有界区间。例如:
check(null, X) :-
!.
check(X, null) :-
!.
check(X, Y) :-
X < Y.
现在,我们可以实现bst/3
谓词,其中对于每个bin/3
复合项,我们检查值是否在范围内,然后递归地使用值作为新边界进行检查:
bst(tip, _, _).
bst(bin(L, V1, R), V0, V2) :-
check(V0, V1),
check(V1, V2),
bst(L, V0, V1),
bst(R, V1, V2).
以下是威廉提供的解决方案的一个微小变化。它只是以不同的方式处理空分支:
bst(Tree) :-
bst(Tree, _).
bst(tree(tip, V, tip), V).
bst(tree(tip, V, R), Rmax) :-
bst(R, Rmax),
V =< Rmax.
bst(tree(L, V, tip), Lmax) :-
bst(L, Lmax),
Lmax =< V.
bst(tree(L, V, R), R) :-
bst(L, Lmax),
bst(R, Rmax),
Lmax =< V, V =< Rmax.
bst(树):-
bst(树,树)。
bst(树(尖端,V,尖端),V)。
bst(树梢、V、R、Rmax):-
英国理工学院(R,Rmax),
V=
以下是Willem作为解决方案提供的一个细微变化。它只是以不同的方式处理空分支:
bst(Tree) :-
bst(Tree, _).
bst(tree(tip, V, tip), V).
bst(tree(tip, V, R), Rmax) :-
bst(R, Rmax),
V =< Rmax.
bst(tree(L, V, tip), Lmax) :-
bst(L, Lmax),
Lmax =< V.
bst(tree(L, V, R), R) :-
bst(L, Lmax),
bst(R, Rmax),
Lmax =< V, V =< Rmax.
bst(树):-
bst(树,树)。
bst(树(尖端,V,尖端),V)。
bst(树梢、V、R、Rmax):-
英国理工学院(R,Rmax),
V=