I am wanting to go through a tree in lisp and find the deepest (or furthest from the root node) by using a tree in the form of a list. So far my idea has been to keep on cutting the tree into left and right sub trees (assuming that the parent node will only ever have two sons like in a binary tree) I will post my code below, because although it compiles it gives me an error of nil not being of a real type. Any advice would be great or even improvements on the code!
I've seen similar question on find the path between nodes but haven't really seen anything useful on how to actually print the deepest node to the screen.
Thanks for looking.
(defun postorder(tree)
(cond ((null tree) 0)
((< (list-length tree) 3) 0)
(t
(append (postorder (left-subtree tree))
(postorder (right-subtree tree))
(list (car tree))))))
(defun tree-depth (sub-tree)
(cond ((null sub-tree) nil)
((atom sub-tree) nil)
(t (+ 1 (max (tree-depth (cadr sub-tree)) (tree-depth (caddr sub-tree)))))))
(defun left-subtree(tree)
(cond ((null tree) nil)
((not (listp tree)) nil)
(t (car (cdr tree)))))
(defun right-subtree(tree)
(cond ((null tree) nil)
((not (listp tree)) nil)
(t (car (cdr (cdr tree))))))
(defun split-tree (tree)
(cond ((null tree)
tree)
((> (tree-depth (left-subtree tree)) (tree-depth (right-subtree tree)))
(split-tree (left-subtree tree)))
((< (tree-depth (left-subtree tree)) (tree-depth (right-subtree tree)))
(split-tree (right-subtree tree)))
((= (tree-depth (left-subtree tree)) (tree-depth (right-subtree tree)))
(first (postorder tree)))))
input would be something along the lines of '(1 (2 (4) (6)) (5 (7) (8))))