views:

443

answers:

3

I seem to be blind at the moment, so I need to ask here. I want to sort a list of tuples which look like that

(id, parent_id, value)

So that it is a representation of the tree as a flattend list of list of tree nodes.

For example the input

(1, None, '...')
(3, 2', '...')
(2, 1, '...')
(4, 1, '...')
(5, 2, '...')
(6, None, '...')

Should sorted like that afterwards

(1, None, '...')
(2, 1, '...')
(3, 2', '...')
(5, 2, '...')
(4, 1, '...')
(6, None, '...')

Any hint would be highly appreciated. Thanks in advance.

+2  A: 
Nicholas Riley
Yes, essentially it is a forest of trees. Every tuple in the list is an item, that can have another tuple as its parent. Your picture models it correctly. It is comparable to a filesystem view, what I want to create.
Oliver Andrich
OK, so how do you want to sort the forest? It looks like you're doing more or less a preorder traversal, then sorting the roots by ID? If so, I'd suggest you consider using another representation that makes them easier to sort, for example nested dictionaries whose keys are the node IDs. Then you can flatten the dictionaries into the list of tuples representation, if you want.
Nicholas Riley
+1  A: 

I'm not sure I've quite follows what you are exactly trying to do, but if you have a forest as a list of nodes, can't you just read it and build the tree structure, then write it out as a bread-first traversal of all the trees? Any particular reason to avoid this?

simon
No, I think, I will have to take this approach. The only thing I wanted to skip was the possible situation, where I have a list of 10.000 tuples (aka database rows), which I put into a dictionary base forest and from which I create a list of tuples again.
Oliver Andrich
A: 

Oliver, if I understand correctly, I think you can either (a) retrieve all tuples from your database into a dictionary or list, and then construct the tree, OR (b) use an ORDER BY clause when you retrieve the tuples so that they are in the order in which you will add them to the tree.

If changes to the tree may be made in your application and then propagated to the database, I would opt for a, but if changes are always made as database inserts, updates or deletes, and apart from these your tree is read-only, then option b should be faster and require less resources.

Roland

Roland