I have a generic tree class, for which I want to implement the IEnumerable interface. The previous questions I found on stackoverflow were a bit different from my problem. I know that I am doing something wring but I don't know what it is. Here is my code:
class Node<T>: IEnumerable<T>
{
private T data;
private LinkedList<Node<T>> children;
public Node(T data)
{
this.data = data;
children = new LinkedList<Node<T>>();
}
public void AddChildNode(Node<T> node)
{
children.AddFirst(node);
}
public void MyTraverse(Node<T> node, List<T> visited)
{
visited.Add(node.data);
foreach (Node<T> kid in node.children)
MyTraverse(kid, visited);
}
public IEnumerator<T> GetEnumerator()
{
return children.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
In the function GetEnumerator() I get a casting error which I don't know how to fix. Can any one help me?
You probably want IEnumerable<Node<T>> interface implementation (you're enumerating nodes Node<T>, not T instances) instead of just IEnumerable<T> one:
class Node<T>: IEnumerable<Node<T>> {
...
public IEnumerator<Node<T>> GetEnumerator() {
return children.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With