【问题标题】:Prolog Postorder Traversal in a general tree using univ使用univ在一般树中进行Prolog后序遍历
【发布时间】:2013-11-23 04:58:14
【问题描述】:

我正在尝试以后序方式遍历 prolog 中的一般树。我发现了很多二叉树后序遍历,但无法将它们用于我的目的。我编写了一个程序,但它只以与输入方式相反的方式打印我的树,即用于输入

?-postorder(a(b,c,d(e,f,g))).
->g f e d c b a true (is what I get)
->b c e f g d a true (what i want to get)

这是我到目前为止编写的代码

postorder([]).
postorder(List):- List =..X , myfun(X).
myfun([A|B]):- atom(A), myfun(B),write(A),write(' ').
myfun([A|B]):- postorder(A),myfun(B).
myfun([]).

我没有获得后序遍历的方法
非常感谢任何帮助

【问题讨论】:

标签: tree prolog postorder


【解决方案1】:

你的参数命名有点混乱

postorder(List):- List =..X , myfun(X).

应该阅读

postorder(Struct):- Struct =.. List, myfun(List).

现在应该更清楚了,您必须在那里编写结构函子:

postorder(Struct):-
  Struct =.. [Functor|Arguments], myfun(Arguments), write(Functor).

此时,您也应该更改 myfun...

作为一个例子,这里是一个紧凑的问题解决方案

postorder(X) :- X =.. [H|As], maplist(postorder, As), write(H).

产生

?- postorder(a(b,c,d(e,f,g))).
bcefgda

【讨论】:

  • 我很抱歉我的命名约定。我是 prolog 的新手,并没有掌握它。那么 maplist 在这里扮演什么角色呢?
【解决方案2】:

另一种方法-

建议 - 我会稍微不同地构建你的树,具体来说,树的形式是

tree(Value,[Subtrees])

其中值类似于a,然后列表是子树列表。叶子有空列表[]

如果这样做,您可以使用这个利用统一的算法-

postorder(tree(VAL,[Child1|ChildList])) :- postorder(Child1),postorder(tree(VAL,ChildList)).
postorder(tree(VAL,[])) :- write(VAL).

输出:

?- postorder(tree(a,[tree(b,[]),tree(c,[]),tree(d,[tree(e,[]),tree(f,[]),tree(g,[])])])).
bcefgda
true .

【讨论】:

    【解决方案3】:

    这是适合我的解决方案。

    postorder([]).
    postorder(Tree):- Tree =..[Parent|Children] , myfun(Children), write(Parent),write(' ').
    myfun([First|Next]):- atom(First), write(First), write(' '), myfun(Next).
    myfun([First|Next]):- postorder(First),myfun(Next).
    myfun([]).
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多