我试图在lisp中遍历一棵树并打印出所有的父子关系。 (5(3)(4(1))(g)(9(6)))(n(8(0))(q)(7)(b(f(c(a)) )))) 我试图把它打印出来的线沿线的东西:lisp树遍历
5>3
5>n
3>4
3>g
3>9
4>1
9>6
n>8
n>q
n>7
n>b
8>0
b>f
f>c
c>a
我当前的代码如下:
(defun par-child-print (l)
(print l)
(cond ((not (null (caadr l)))
(print "start")
(print (car l))
(print ">")
(print (caadr l))
(print "end")
(cond ((not (atom (car l))) (when (not (eq (car l) NIL)) (par-child-print (car l)))));
(when (not (eq (cdr l) NIL)) (par-child-print (cdr l)))
)
(t
)));
的问题是,我只输出有时打印父母(也没有通过整个树)。有任何想法吗?
我也有这样的,使得它在整个树,但并不甚至企图跟踪的父母:
(defun atom-print (l)
(print l)
(cond ((atom l) (print l));
(t
(when (not (eq (car l) NIL)) (atom-print (car l)))
(when (not (eq (cdr l) NIL)) (atom-print (cdr l)))
)));