Help me understand Inorder Traversal without using recursion

后端 未结 14 2695
别跟我提以往
别跟我提以往 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条回答
  •  -上瘾入骨i
    2020-12-12 12:37

    Simple iterative inorder traversal without recursion

    '''iterative inorder traversal, O(n) time & O(n) space '''
    
    class Node:
        def __init__(self, value, left = None, right = None):
            self.value = value
            self.left = left
            self.right = right
    
    def inorder_iter(root):
    
        stack = [root]
        current = root
    
        while len(stack) > 0:
            if current:
                while current.left:
                    stack.append(current.left)
                    current = current.left
            popped_node = stack.pop()
            current = None
            if popped_node:
                print popped_node.value
                current = popped_node.right
                stack.append(current)
    
    a = Node('a')
    b = Node('b')
    c = Node('c')
    d = Node('d')
    
    b.right = d
    a.left = b
    a.right = c
    
    inorder_iter(a)
    

提交回复
热议问题