-2 lisp printing tree recursion common-lisp
INPUT :( A(B(D(E)(F)))(C)(K))我目前有两个函数,它给我一个OUTPUT:
一个
乙
C
ķ
乙
d
d
Ë
F
Ë
零
但是我需要这样的输出:
a:bck
b:d
c:
k:
d:ef
E:
F:
要么
一个
BSK
d
EF
(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)))))
Run Code Online (Sandbox Code Playgroud)
节点
您应该定义的第一件事:节点的一些数据结构函数.
nodep 东西 - >是节点吗?node-name node - >返回节点的名称node-childrennode - >返回节点的子节点广度优先
然后我将定义一个以广度优先顺序遍历树的函数.
breadth-first 树 fn &optional 队列此函数将以FN广度优先顺序调用树的所有元素.
FN在当前节点上调用该函数将上面的循环写为递归函数.
打电话给BREADTH-FIRST
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:
Run Code Online (Sandbox Code Playgroud)