Efficient way to walk through an object tree?


Efficient way to walk through an object tree?



I've got a set of TreeNodes, each of which has an id, a Collection of parent nodes, and a collection of child nodes.

For a given node Id, I'm looking for an efficient way to generate all the links that pass through that node. So in short, start at the node, and iterate through all its children. If a node has more than one child, create a link for each child. The traverse the children etc..

I'd also like to be able to do this in an 'upward' direction, through the parent nodes.

Is there a simple algorithm to do this?

EDIT: Oh, and I'd like to be able to output the id's of all the nodes in a given chain...




K- Means algorithm

1:



Algorithm for Determining Tic Tac Toe Game Over
You are looking for a Breadth First or Depth First Search.


help me improve my basic point to point move animation algorithm
At first it is not more than the following (this is depth first search)..
Is timsort general-purpose or Python-specific?
Visit(Node node) {     foreach (Node childNode in node.Children)     {         Visit(childNode);     }      DoStuff(node); } 
The problem is that the graph may contain cycles, hence the algorithm will enter infinite loops.


KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm
To get around this you must remember visited nodes by flaging them or storing them in a collection.


Fast Algorithm to Generate 500,000 html file
If the graph has no cycles - for example if it is a tree - this short algorithm will already work..
How to split long strings into fixed array items
And by the way, if a TreeNode has multiple parents, it's not a tree but a graph node..
Optimized way to re-order numbering using C#


2:


Well, if the nodes have a reference to the parent, it's simple as getting the parent recursively (once in a tree, each node has only one (or none at all, if it is a root) parent.. If there's no such reference, than you could use a breadth-first search, for instance, having as initial set your collection of parent nodes.. -- EDIT --. Once a node may have more than one parent, then you're dealing with a graph.

There are also graph traversal algorithms (see table at the side).. Make sure that, if your graph has a cycle, you won't end up having a infinite loop.


3:


You might want to check out depthFirstEnumeration() and breadthFirstEnumeration() on DefaultMutableTreeNode.

However, this doesn't solve your problem of wanting to navigate the tree in a bottom-up fashion..


4:


This is a usecase of the visitor pattern.



94 out of 100 based on 74 user ratings 1174 reviews