Help me understand Inorder Traversal without using recursion

后端 未结 14 2722
别跟我提以往
别跟我提以往 2020-12-12 11:44

I am able to understand preorder traversal without using recursion, but I\'m having a hard time with inorder traversal. I just don\'t seem to get it, perhaps, because I have

14条回答
  •  天涯浪人
    2020-12-12 12:34

    I think part of the problem is the use of the "prev" variable. You shouldn't have to store the previous node you should be able to maintain the state on the stack (Lifo) itself.

    From Wikipedia, the algorithm you are aiming for is:

    1. Visit the root.
    2. Traverse the left subtree
    3. Traverse the right subtree

    In pseudo code (disclaimer, I don't know Python so apologies for the Python/C++ style code below!) your algorithm would be something like:

    lifo = Lifo();
    lifo.push(rootNode);
    
    while(!lifo.empty())
    {
        node = lifo.pop();
        if(node is not None)
        {
            print node.value;
            if(node.right is not None)
            {
                lifo.push(node.right);
            }
            if(node.left is not None)
            {
                lifo.push(node.left);
            }
        }
    }
    

    For postorder traversal you simply swap the order you push the left and right subtrees onto the stack.

提交回复
热议问题