def preOrderIter(root):
    ''' a much easier way, use a stack, push right first and then push left '''
    if not root: return
    s = Stack()
    s.push(root)
    while not s.isEmpty():
        curr = s.pop()
        print curr.value
        if curr.right:
            s.push(curr.right)
        if curr.left:
            s.push(curr.left)


bst = BinarySearchTree()
bst.put(6)
bst.put(3)
bst.put(4)
bst.put(7)
bst.put(9)
bst.put(2)
print bst
print '==== post recur ===='
postOrderRecur(bst.root)
print '==== post iter===='
postOrderIter(bst.root)
print '==== post iter 2===='
postOrderIter2(bst.root)
print '==== pre iter===='
preOrderIter(bst.root)
print '==== in recur===='
Пример #2
0
def bfsIterative(node):
    if node is None:
        return []
    res = []
    q = Queue()
    q.enqueue(node)
    while not q.isEmpty():
        tmp = q.dequeue()
        res.append(tmp.value)
        if tmp.left:
            q.enqueue(tmp.left)
        if tmp.right:
            q.enqueue(tmp.right)
    return res


bst = BinarySearchTree()
bst.put(5)
bst.put(2)
bst.put(4)
bst.put(3)
bst.put(1)
bst.put(8)
bst.put(7)
bst.put(9)
print bst

print "dfs iterative: ", dfsIterative(bst.root)
print "dfs recursive: ", dfsRecursive(bst.root)
print "bfs iterative: ", bfsIterative(bst.root)