0

I have built a tree structure and had a few issues with it that were solved in the question Traversing a Tree Structure

I would like to implement a method with an action in the TreeNode class. I am having difficulty understanding how to do this and implementing it. What I have so far is:

            internal void Traverse(Action<TreeNode<T>> action)
            {
                action(TreeNode<T>);
                foreach (var child in this.children)
                    child.Traverse(action);
            }

Any explanation and help would be greatly appreciated.

I am getting errors:

Error 667 TreeNode' is a 'type' but is used like a 'variable'

Error 668 'System.Collections.Generic.KeyValuePair>' does not contain a definition for 'Traverse' and no extension method 'Traverse' accepting a first argument of type 'System.Collections.Generic.KeyValuePair>' could be found (are you missing a using directive or an assembly reference?)

1 Answer 1

0

in the first line, you need to pass a variable.
Basically, call action just like you would a reglular function:

action(myTreeNode)

The second error is because you forgot to select the "Values" from the dictionary.

       internal void Traverse(Action<TreeNode<T>> action)
       {
         action(this);
         foreach (var child in this.children.Values)
           child.Traverse(action);
       }

I've implemented functions like this before, but the problem is that you're locking yourself into one type of traversal. I'd recommend you stick to using foreach instead, that way you can modify your traversal using LINQ. In your last post, you showed that you made your tree implement IEnumerable. That's all you need to enable LINQ.

So, you can accomplish your current requirement like this:

foreach (var node in MyTree)
{
  // do stuff to node here
{

And in the future, you can do cool things like this:

foreach (var node in MyTree.Where(n => n.Type == somethingOfInterest))
{
  // do stuff to node here
{
3
  • Thank you. This worked but I don't get the action(this) part. Yes, I understand the values partof the dictionary error. Thank you.
    – PBrenek
    Nov 21, 2014 at 1:07
  • 1
    I assumed that Traverse is a member of the TreeNode<T> class.
    – Adam C
    Nov 21, 2014 at 2:14
  • Thank you. So are you suggesting I take the Traverse method out of the TreeNode class and place it in the Tree class?
    – PBrenek
    Nov 21, 2014 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.