Last active
August 29, 2015 14:17
-
-
Save MarkLavrynenko/9bec7928d30a47507988 to your computer and use it in GitHub Desktop.
Tree Traversal Lisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(load "1.lsp") | |
(setq tree '(1 (2 5) 6 (10 (14 (25 27) 40)))) | |
(print tree) | |
(defun traverse-tree(tree depth) | |
(if (atom tree) | |
(progn (funcall func tree) (return-from traverse-tree)) | |
) | |
(let ((list-len (length tree))) | |
;(format t "~%Depth is ~0$" depth) | |
(unless (atom tree) | |
(mapcar 'traverse-tree tree (make-list list-len :initial-element (+ 1 depth))) | |
) | |
;(format t "~%Depth is ~0$" depth) | |
) | |
) | |
(defun flatten(list) | |
(let ((leafs '())) | |
(defun collect-leaf(leaf) | |
(push leaf leafs) | |
) | |
(setq func 'collect-leaf) | |
(traverse-tree tree 0) | |
(nreverse leafs) | |
(return-from flatten leafs) | |
) | |
) | |
(print (flatten tree)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment