Saturday, March 4, 2017

Non Recursive Pre-Order Traversal

public IEnumerator PreOrderTraversal()
        {
            if (Head != null)
            {
                Stack> stack = new Stack>();
                BinaryTreeNode current = Head;
                stack.Push(null);

                while (stack.Count!=0)
                {
                    if (current != null)
                    {
                        yield return current.Value;
                        if (current.Right != null)
                            stack.Push(current.Right);
                        if (current.Left != null)
                        {
                            current = current.Left;
                        }
                        else
                        {
                            current = stack.Pop();
                        }
                    }
                }
            }
        }

Non Recursive In-Order Traversal C#

 public IEnumerator InOrderTraversal()
        {
            BinaryTreeNode current = Head;
            Stack> stack = new Stack>();
            stack.Push(null);

            while (stack.Count != 0)
            {
                while (current != null)
                {
                    stack.Push(current);
                    current = current.Left;
                }
                current = stack.Pop();
                if (current != null)
                {
                    yield return current.Value;
                    current = current.Right;
                }
            }
        }