C
C#2y ago
xyrile

❔ Design pattern Iterator

So I was working with Node<T> in PreOrder Traversal when i try to test it gives me an error message saying Something is wrong in our systems, your code took too long to execute. Here's my code
public class Node<T>
{
public T value;
public Node<T> left, right, parent;

public Node(T value)
{
this.value = value;
}

public Node(T value, Node<T> left, Node<T> right)
{
this.value = value;
this.left = left;
this.right = right;

left.parent = right.parent = this;
}

public IEnumerable<T> PreOrder
{
get
{
return new PreOrderIterator<T>(this);
}
}
}
public class PreOrderIterator<T> : IEnumerable<T>
{
private Stack<Node<T>> stack = new Stack<Node<T>>();
public PreOrderIterator(Node<T> root)
{
stack.Push(root);
}
public IEnumerator<T> GetEnumerator()
{
return GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public class Node<T>
{
public T value;
public Node<T> left, right, parent;

public Node(T value)
{
this.value = value;
}

public Node(T value, Node<T> left, Node<T> right)
{
this.value = value;
this.left = left;
this.right = right;

left.parent = right.parent = this;
}

public IEnumerable<T> PreOrder
{
get
{
return new PreOrderIterator<T>(this);
}
}
}
public class PreOrderIterator<T> : IEnumerable<T>
{
private Stack<Node<T>> stack = new Stack<Node<T>>();
public PreOrderIterator(Node<T> root)
{
stack.Push(root);
}
public IEnumerator<T> GetEnumerator()
{
return GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
2 Replies
Anton
Anton2y ago
well you have infinite recursion in your GetEnumerator the node should be enumerable, the iterator should be ienumerator and you still have to implement the enumerator logic your code right now does effectively nothing
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server