I need to traverse a tree quickly, and I would like to do it in parallel. I\'d rather use the parallel extensions than manually spin up a bunch of threads.
My current co
I might be missing something, but I don't see the need for a while
at all. The while
is just ensuring that you iterate over every node.
Instead just call your function recursively for each node in the tree.
public void Traverse(Node root)
{
if (root.Property = someValue) DoSomething(node);
Parallel.ForEach(root.Children, node => Traverse(node));
}
edit: of course the alternative, if you prefer to process horizontally rather than vertically and your expensive operation is DoSomething, is to do the Traverse
first.
public IEnumerable Traverse(Node root)
{
// return all the nodes on this level first, before recurring
foreach (var node in root.Children)
{
if (node.Property == someValue)
yield return node;
}
// next check children of each node
foreach (var node in root.Children)
{
var children = Traverse(node);
foreach (var child in children)
{
yield return child;
}
}
}
Parallel.ForEach(Traverse(n), n => DoSomething(n));