Non-Recursive Binary Tree Traverse in C#

private void NonRecursive()
{
TreeNode currNode = root;
while (true)
{
if (currNode == null)
break;

if (currNode.Left != null && currNode.Left.Visited != 1)
currNode = currNode.Left;
else if (currNode.Right != null && currNode.Right.Visited != 1)
currNode = currNode.Right;
else if (currNode.Visited == 0)
{
Console.Write(currNode.Value + " ");
currNode.Visited = 1;
} else
currNode =currNode.Parent;
}
}

There is another way using a stack but using a Stack is not so Iterative approach for me.

Leave a Reply

Your email address will not be published. Required fields are marked *