二叉树同构

时间:2009-10-11 21:14:00

标签: computer-science prolog

我有一个编写其他东西的任务,一组prolog谓词,用于确定任何两个二叉树是否彼此同构。谓词还必须能够为任何给定的二叉树提供所有同构图。

这是我到目前为止所做的,它除了返回重复项外都有效。

% Clause: btree_iso
%
% Specification:
% --------------
% Satisfied when the two binary-tree parameters are isomorphic. Two binary
% trees are isomorphic if one can be derived from the other by changing the
% order of the branches. Either of the parameters may be instantiated with a
% variable when btree_iso is used in a top-level goal.
%
% Description:
% ------------
% Base case for the binary tree iso morphism predicate.
% Both sides are leaves.
btree_iso( leaf, leaf ).

% Description:
% ------------
% TODO
btree_iso( node( BTL1, X, BTR1 ), node( BTL2, X, BTR2 ) ) :- btree_iso( BTL1, BTL2 ),
                                                             btree_iso( BTR1, BTR2 ).
% Description:
% ------------
% TODO
btree_iso( node( BTL1, X, BTR1 ), node( BTL2, X, BTR2 ) ) :- btree_iso( BTL1, BTR2 ),
                                                             btree_iso( BTR1, BTL2 ).

预期输出:

? - btree_iso(node(node(leaf,3,leaf),3,node(leaf,5,leaf)),BT).
BT = node(node(leaf, 3, leaf), 3, node(leaf, 5, leaf)) ;
BT = node(node(leaf, 5, leaf), 3, node(leaf, 3, leaf)).

我的输出

?- btree_iso(node(node(leaf,3,leaf),3,node(leaf,5,leaf)),BT).
BT = node(node(leaf, 3, leaf), 3, node(leaf, 5, leaf)) ;
BT = node(node(leaf, 3, leaf), 3, node(leaf, 5, leaf)) ;
BT = node(node(leaf, 3, leaf), 3, node(leaf, 5, leaf)) ;
BT = node(node(leaf, 3, leaf), 3, node(leaf, 5, leaf)) ;
BT = node(node(leaf, 5, leaf), 3, node(leaf, 3, leaf)) ;
BT = node(node(leaf, 5, leaf), 3, node(leaf, 3, leaf)) ;
BT = node(node(leaf, 5, leaf), 3, node(leaf, 3, leaf)) ;
BT = node(node(leaf, 5, leaf), 3, node(leaf, 3, leaf)).

显然这些都是重复,我似乎找不到合适的位置来放置剪切,因此谓词不会返回重复。我还尝试为只有一个叶子的节点编写另外两个谓词,另一个节点但是它们似乎没有帮助。

关于如何阻止重复的任何建议?

1 个答案:

答案 0 :(得分:1)

想想当BT = node(leaf,X,leaf)时会发生什么。您的解决方案为此案例提供了两个相同的解叶子交换的地方和不交换叶子的地方。

您需要明确处理此案例,只返回一个解决方案。由于此案例可能与其他条款类似,因此您还需要确保多个子句不能满足此案例。

相关问题