【发布时间】:2021-12-01 08:51:01
【问题描述】:
我编写了一个函数 DFS,它以从右到左的 DFS 顺序遍历搜索树。例如,(DFS '(((((L E) F) T))) 应该返回 (T F E L)。我成功创建的以下代码可以做到这一点,但是它仍然在结果中包含 NIL 值。如何仅删除 nil 值?
; Following code returns right answer, but with nils.
; For example. running the function on
; '((((L E) F) T)) will return ((((NIL . T) . F) . E) . L)
; but not (T F E L)
(defun DFS (tree)
(cond ((null tree) ()) ;current node is null, return nil
;Checks if car of current node is a list. If yes, recursively call DFS and append car to its cdr
((listp (car tree)) (DFS (append (car tree) (cdr tree))))
;Else, call recursively DFS on cdr of current node and append to car
(T (cons (DFS (cdr tree)) (car tree)))))
【问题讨论】:
-
我认为用英文记录 COND 子句应该做什么是个好主意->。在代码中使用 cmets。否则我们必须猜测你的意图是什么。
-
它应该如何处理,例如,((L E) (F T))?它应该返回 ((F T) (L E))、((T F) (E L)) 还是 (T F E L)?
-
这里有一个提示->您的评论说:“附加到汽车”,但您没有附加,您正在调用缺点。附加也需要在列表上工作。
标签: lisp common-lisp depth-first-search