Re: All paths through a tree
- From: "Kaz Kylheku" <kkylheku@xxxxxxxxx>
- Date: 27 Sep 2006 15:02:27 -0700
Blaine wrote:
Given a tree like:
(77 (237 (228 (234 (231 266) 266)) (234 (231 266) 266)))
I would like to list all the paths from the source node to the terminal
nodes:
((77 237 228 234 231 266)
(77 237 228 234 266)
(77 237 234 231 266)
(77 237 234 266))
What do you mean by terminal nodes and paths? There is more than one
way in which structures of conses and atoms represent trees; it depends
on your convention. You don't suppose that this is important? Staring
into my crystal ball, I see that according to your definition,
something of the form
(X Y Z ...)
is a node labelled by X which is an atom. Y and Z are its children, and
they are nodes. A node can also be an atom, in which case it's a
terminal.
Thus in your above list, there are indeed four terminal nodes.
A path is simply a list of the names of the non-terminal nodes and the
terminal atom.
I've been struggling with this for a few days now, and I just can't get
it to work.
Hee hee. Here you go:
(defun paths (list)
(let (path-list)
(labels ((traverse (list stack)
(destructuring-bind (label &rest children) list
(push label stack)
(dolist (child children)
(cond
((atom child)
(push child stack)
(push (reverse stack) path-list)
(pop stack))
(t
(traverse child stack)))))))
(traverse list nil)
(nreverse path-list))))
Test case:
(paths '(77 (237 (228 (234 (231 266) 266)) (234 (231 266) 266))))
->
((77 237 228 234 231 266) (77 237 228 234 266) (77 237 234 231 266)
(77 237 234 266))
Do your own homework next time.
.
- References:
- All paths through a tree
- From: Blaine
- All paths through a tree
- Prev by Date: Re: [CLOS] Ensuring a method exists
- Next by Date: Re: Ensuring a method exists
- Previous by thread: Re: All paths through a tree
- Next by thread: Re: All paths through a tree
- Index(es):
Relevant Pages
|