Reputation:
Given a list/tree of the form : (node1 (node2) (node3 (node4) (node5)) (node6)) I should be able to find out the depth at which a searched node resides.
This is what I've done so far:
(defun search-it (lst level n)
(cond ((null lst) nil)
((and (atom (car lst)) (equal (car lst) n)) level)
((atom (car lst)) (search-it (cdr lst) level n))
(t (cons (search-it (car lst) (+ 1 level) n)
(search-it (cdr lst) level n)))))
(defun search-node (l n)
(search-it l 0 n))
For this particular implementation I have a correct solution, but what bothers me is that I can't get rid of some nil lists. For example:
(search-node '(1 (2) (3 (4) (6) (7) (8 (9) (10)))) 6)
(NIL (NIL 2 NIL (NIL NIL)))
The solution is correct if we consider the root node at depth 0. Now of course I could add some code to the search-node function to remove everything except the solutions, I can't help but feel that it's not the most elegant way to do this.
LE: The expected result should be the depth or a list of depths in case the number appears more than once.
Some pointers anyone? PS: lisp newbie
Upvotes: 4
Views: 136
Reputation: 139251
Generally return a list of depths. So, if an item is found, then return the list of the single depth. If you branch to the first and rest of the list, then don't 'cons', but 'append'.
Note also that your code does not find all depths.
CL-USER 6 > (search-node '(6 (6)) 6)
0
Upvotes: 2