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();
                        }
                    }
                }
            }
        }

No comments:

Post a Comment