我試圖在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)))
)));