非递归遍历二叉树

class Node(object):
    def __init__(self, v):
        self.value = v
        self.left = None
        self.right = None


root = Node(1)

root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)


def inorder(root):
    current = root
    stack = []

    while True:
        if current:
            stack.append(current)
            current = current.left
        elif stack:
            current = stack.pop()
            print(current.value, end=' ')
            current = current.right
        else:
            break


def preorder(root):
    current = root
    stack = []

    while True:
        if current:
            stack.append(current)
            print(current.value, end=' ')
            current = current.left
        elif stack:
            current = stack.pop()
            current = current.right
        else:
            break


def postorder(root):
    current = root
    stack = []
    prev = None

    while True:
        if current:
            stack.append(current)
            current = current.left
        elif stack:
            current = stack[len(stack) - 1]

            if current.right is None or current.right == prev:
                print(current.value, end=' ')
                stack.pop()
                prev = current
                current = None
            else:
                current = current.right

        else:
            break


print(
    r'''
     1
    / \
   2   3
  / \
 4   5
'''
)


print('\n--------- Pre Order ---------------')

preorder(root)

print('\n--------- In Order ---------------')

inorder(root)

print('\n----------Post Order -------------')

postorder(root)

你可能感兴趣的:(非递归遍历二叉树)