Search code examples
algorithmbinary-search-treetree-traversaliterationinorder

How to do in-order traversal of a BST without recursion or stack but using parent pointers?


Is it possible to do an iterative in-order-traversal on a BST whose node has a parent pointer (the parent of the root is null) without using a visited flag or a stack?

I googled and didn't find a reply. The point is, how can I know - at a certain node - that I've just come to it vs I've finished everything underneath it?


Solution

  • You can do that, you just need to remember the last visited node along with the current node. Doing this is not disallowed by the problem statement: both visited flag on each node and a stack are (worst case) O(n), remembering the last node is just O(1).

    In C#, the algorithm could look like this:

    static void Walk(Node node)
    {
        Node lastNode = null;
        while (node != null)
        {
            if (lastNode == node.Parent)
            {
                if (node.Left != null)
                {
                    lastNode = node;
                    node = node.Left;
                    continue;
                }
                else
                    lastNode = null;
            }
            if (lastNode == node.Left)
            {
                Output(node);
    
                if (node.Right != null)
                {
                    lastNode = node;
                    node = node.Right;
                    continue;
                }
                else
                    lastNode = null;
            }
            if (lastNode == node.Right)
            {
                lastNode = node;
                node = node.Parent;
            }
        }
    }