Tree path in a List of Lists

回眸只為那壹抹淺笑 提交于 2019-12-08 06:40:20

问题


I want to build a predicate (Prolog) that takes a tree and returns a list of lists and each list is a tree path. The tree is defined as tree(Root,LeftTree,RightTree). Do you have any suggestions, please?


回答1:


This is quite unusual (it is more common to ask for example for a relation between a tree and a flat list of all its nodes, for which DCGs are a good fit), maybe like this:

tree_list(nil, []).
tree_list(tree(Node,Left,Right), [Lefts,Node,Rights]) :-
        tree_list(Left, Lefts),
        tree_list(Right, Rights).

Example:

?- tree_list(tree(a,tree(b,nil,tree(d,nil,nil)),tree(c,nil,nil)), Ts).
Ts = [[[], b, [[], d, []]], a, [[], c, []]].

This representation is wasteful (you know that all non-empty lists will have 3 elements, so why not use a ternary term instead of a list?) and in my opinion unnecessary (because you already have the tree representation in the first place), but who knows what it is good for...



来源:https://stackoverflow.com/questions/10065675/tree-path-in-a-list-of-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!