1
votes

I've got a tree which is populated by Node objects. Each node has an ArrayList which stores its children nodes as there can be an unspecified amount of children, unlike in a binary tree.

How can I traverse the tree to find a specific node if each node has a number of children, where each child has its own children in turn, and so on. I'm just looking for a generic way of doing this iteratively, for example using a function which searches through a node's arrayList (storing children), and each child's subsequent children's array lists too.

Any suggestions?

UPDATE

This is what I've tried so far:

return 
(
    (StrangeNode)current.ChildrenList
        .SingleOrDefault(c => 
            c.GetType().Name.ToString().Equals("StrangeNode"))
).myArrayList;
2
mattgemmell.com/2008/12/08/what-have-you-tried This sounds like an attempt at getting SO to do your homework?Justin Pihony
It's not homework actually, I'm trying to implement a tree which is to have a special type of node at certain points in the tree (i.e. a different class)Palindrome
He didn't mean it literally, what have you tried?Louis Kottmann
This is what I've tried so far, but to no avail: return ((StrangeNode)current.ChildrenList.SingleOrDefault(c => c.GetType().Name.ToString().Equals("StrangeNode"))).myArrayList;Palindrome

2 Answers

0
votes

Iteratively you could do something like this:

List<Node> nodes = new List<Node>();
nodes.add( rootnode )

for (int i=0; i < nodes.count; i++)
{

Node currentNode = nodes[i];

//do the processing to check here

nodes.add(currentNode.children) //not 100% sure how to do this, but you get the idea

}

If you want it done recursily its just a depth-first, very easy.

0
votes

The two most obvious ways are a depth first search and a breadth first search. You can find examples of both in any algorithms text book or online by searching for it. You can implement that depth first search recursively in 3-10 lines of code.