I m trying to implement Tree Traversal PreOrder using yield return which returns an IEnumerable
private IEnumerable<T> Preorder(Node<T> node)
{
while(node != null)
{
yield return node.Data;
yield return node.LeftChild.Data;
yield return node.RightChild.Data;
}
}
In this case, it goes into infinite loop and yes I know that I need to keep traversing. How can this be done?
If the LeftChild or RightChild is null, throws a null exception. I think at that point i need yield break;
I assume, inorder and postorder would be similar too, any ideas?
I have the Resursive version, that works well.
public void PreOrderTraversal(Node<T> node)
{
if(node!=null)
{
Console.Write(node.Data);
}
if (node.LeftChild != null)
{
PreOrderTraversal(node.LeftChild);
}
if (node.RightChild != null)
{
PreOrderTraversal(node.RightChild);
}
}
Thanks.