Help me understand Inorder Traversal without using recursion

后端 未结 14 2718
别跟我提以往
别跟我提以往 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:46

    @Victor, I have some suggestion on your implementation trying to push the state into the stack. I don't see it is necessary. Because every element you take from the stack is already left traversed. so instead of store the information into the stack, all we need is a flag to indicate if the next node to be processed is from that stack or not. Following is my implementation which works fine:

    def intraverse(node):
        stack = []
        leftChecked = False
        while node != None:
            if not leftChecked and node.left != None:
                stack.append(node)
                node = node.left
            else:
                print node.data
                if node.right != None:
                    node = node.right
                    leftChecked = False
                elif len(stack)>0:
                    node = stack.pop()
                    leftChecked = True
                else:
                    node = None
    

提交回复
热议问题