using System;
using System.Collections.Generic;
using System.Collections;
/// <summary>
/// Abstract node
/// </summary>
/// <typeparam name="T"></typeparam>
abstract class TreeNode<T> where T : TreeNode<T>
{
public T LeftNode { get; set; }
public T RightNode { get; set; }
}
/// <summary>
/// Tree class
/// </summary>
/// <typeparam name="T"></typeparam>
class Tree<T> where T : TreeNode<T>
{
/// <summary>
/// Root node
/// </summary>
public T RootNode { get; set; }
public IEnumerator GetEnumerator()
{
//Reserve nodes which have right node.
Stack<T> stack = new Stack<T>();
//Current node instance
T currentNode = RootNode;
//While current node was set as the lat node's right node, exit the cycle
while (currentNode != null)
{
//Output current node
yield return currentNode;
//If current node has right node, add it to stack
if (currentNode.RightNode != null)
{
stack.Push(currentNode);
}
//If current node has left node, set rge current node as the left node
if (currentNode.LeftNode != null)
{
currentNode = currentNode.LeftNode;
}
else
{
//If current node doesn't has left node, go to stack to get the first right node, and go on the cycle
if (stack.Count != 0)
{
currentNode = (T)stack.Pop().RightNode;
}
else
{
break;
}
}
}
}
}