【问题标题】:How to print tree in lisp without dolist, only recursion? [closed]如何在没有dolist的lisp中打印树,只有递归? [关闭]
【发布时间】:2018-02-23 17:09:22
【问题描述】:

输入:(A(B(D(E)(F)))(C)(K)) 我目前有两个函数,这给了我一个输出:

一个

C

K

D

D

E

F

E

没有

但是我需要这样的输出:
a: b c k
b: d
c:
克:
d: e f

e:

f:

一个

b s k

d

e f

(defun print-children (s)
   (cond ((null (caar (cdr s))) nil) 
         (t (print (caar (cdr s))) (print-children (cdr s)))))

(defun print-tree (s)
  (cond ((null s) nil)
        ((atom (car s)) (print (car s)) (print-children s) (print-tree (cdr s)))
        (t (print-tree (car s)))))

【问题讨论】:

  • 我不明白这个问题。 'all from the new line' - 这是什么意思?您的问题缺少预期输入和输出的有用示例。
  • @RainerJoswig 改了,更清楚了吗?
  • @RainerJoswig 新加入堆栈,忘记添加所有信息
  • 这些函数应该做什么?我可以阅读代码,但例如我不知道您打算用 PRINT-LEVEL 做什么。
  • @RainerJoswig 打印级别(我将其重命名为 print-children)打印主节点的直接子节点。整个问题在于打印一棵树 BREADTH FIRST。

标签: recursion printing tree lisp common-lisp


【解决方案1】:

节点

你应该定义的第一件事:节点的一些数据结构函数。

  • nodep 事物 -> 事物是节点吗?
  • node-name node -> 返回节点名称
  • node-childrennode -> 返回节点的子节点

广度优先

然后我会定义一个函数以广度优先顺序遍历树。

  • breadth-first fn &optional 队列

此函数将按广度优先顺序对树的所有元素调用 FN

  1. 如果没有节点,结束
  2. 从队列中取出第一个节点作为当前节点
  3. 将当前节点的子节点推到队列末尾
  4. 在当前节点调用FN函数
  5. tree fn queue 调用自己

把上面的这个循环写成递归函数。

调用广度优先

CL-USER 76 > (breadth-first '(A (B (D (E)
                                      (F)))
                                (C)
                                (K))
                            (lambda (node)
                              (princ (node-name node))
                              (princ ":")
                              (mapc (lambda (child)
                                      (princ (node-name child)))
                                    (node-children node))
                              (terpri)))
A:BCK
B:D
C:
K:
D:EF
E:
F:

【讨论】:

  • 没有 lambda 会怎样?
  • 我们的任务仅限于基本功能:car, cdr, cons, cond, for, print, list-length, format, apply, atom, setq
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
相关资源
最近更新 更多