从二叉树的叶子

时间:2016-12-23 10:12:16

标签: prolog

我有一个像这样的二叉树:

tree(T) :-
    T = btree("classes",
              [
              btree("class1",
                    [
                    btree("thomas", [])
                    ]
              ),
              btree("class2",
                    [
                    btree("peter", []),
                    btree("liz", [])
                    ]
              ),
              btree("class3",
                    [
                    btree("anna", []),
                    btree("jack", [])
                    ]
              )]
        ).

我想创建一个谓词tree_leaf(T,Leaf),它给出了二叉树中的所有叶子。谓词应该适用于每个二叉树。

1 个答案:

答案 0 :(得分:2)

这是我的实施:

tree_leaf(btree(X,[]),btree(X,[])).
tree_leaf( btree(_,L),Leaf):-loop(L,Leaf).

loop([X|_],Leaf):-tree_leaf(X,Leaf).
loop([_|T],Leaf):-loop(T,Leaf).

示例:

?- tree(T),tree_leaf(T,Leaf).
T = btree("classes", [btree("class1", [btree("thomas", [])]), btree("class2", [btree("peter", []), btree("liz", [])]), btree("class3", [btree("anna", []), btree("jack", [])])]),
Leaf = btree("thomas", []) ;
T = btree("classes", [btree("class1", [btree("thomas", [])]), btree("class2", [btree("peter", []), btree("liz", [])]), btree("class3", [btree("anna", []), btree("jack", [])])]),
Leaf = btree("peter", []) ;
T = btree("classes", [btree("class1", [btree("thomas", [])]), btree("class2", [btree("peter", []), btree("liz", [])]), btree("class3", [btree("anna", []), btree("jack", [])])]),
Leaf = btree("liz", []) ;
T = btree("classes", [btree("class1", [btree("thomas", [])]), btree("class2", [btree("peter", []), btree("liz", [])]), btree("class3", [btree("anna", []), btree("jack", [])])]),
Leaf = btree("anna", []) ;
T = btree("classes", [btree("class1", [btree("thomas", [])]), btree("class2", [btree("peter", []), btree("liz", [])]), btree("class3", [btree("anna", []), btree("jack", [])])]),
Leaf = btree("jack", []) ;
false.

正如你所看到的,我使用了树谓词,以便每次都不输入整个树,所以它也返回树T. 上面的实现在找到一个叶子时停止,对于每个不是叶子的节点,它为节点的每个子节点调用tree_leaf/2