class TreeNode:
#tree structure
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Stack:
"""
Data structure that implements a last-in-first-out (LIFO)
queue policy.
"""
def __init__(self):
self.list = []
def push(self,item):
"""
Push 'item' onto the stack
"""
self.list.append(item)
def pop(self):
"""
Pop the most recently pushed item from
the stack
"""
return self.list.pop()
def isEmpty(self):
"""
Returns true if the stack is empty
"""
return len(self.list) == 0
def top(self):
#retrieve the top item
if self.isEmpty():
return None
else:
return self.list[-1]
class Queue:
"""
Data structure that implements a first-in-first-out (FIFO)
queue policy.
"""
def __init__(self):
self.list = []
def push(self,item):
"""
Enqueue the 'item' into the queue
"""
self.list.insert(0,item)
def pop(self):
"""
Dequeue the earliest enqueued item still in the queue. This
operation removes the item from the queue.
"""
return self.list.pop()
def isEmpty(self):
"""
Returns true if the queue is empty.
"""
return len(self.list) == 0
def visit(x):
#visit function
print x,
def PreOrder(a_tree,a_visit):
#search the tree in pre-order
temp=a_tree
a_stack=Stack()
while temp!=None or (not a_stack.isEmpty()):
while temp!=None:
a_visit(temp.val)
a_stack.push(temp)
temp=temp.left
if not a_stack.isEmpty():
temp=a_stack.pop()
temp=temp.right
print
def InOrder(a_tree,a_visit):
#search the tree in in-order
temp=a_tree
a_stack=Stack()
while temp!=None or (not a_stack.isEmpty()):
while temp!=None:
a_stack.push(temp)
temp=temp.left
if not a_stack.isEmpty():
temp=a_stack.pop()
a_visit(temp.val)
temp=temp.right
print
def PostOrder(a_tree,a_visit):
#search the tree in post-order
temp=a_tree
a_stack=Stack()
pre_temp=None
while temp!=None or (not a_stack.isEmpty()):
while temp!=None:
a_stack.push(temp)
temp=temp.left
temp=a_stack.top()
if temp.right==pre_temp or temp.right==None:
a_stack.pop()
pre_temp=temp
a_visit(temp.val)
temp=None
else:
temp=temp.right
print
def LevelOrder(a_tree,a_visit):
#search the tree in level-order
temp=a_tree
a_queue=Queue()
a_queue.push(temp)
while not a_queue.isEmpty():
temp=a_queue.pop()
a_visit(temp.val)
if temp.left!=None:
a_queue.push(temp.left)
if temp.right!=None:
a_queue.push(temp.right)
print
def ProduceATree():
#produce a complete three-level bi-tree
a_tree=TreeNode(1)
a_tree.left=TreeNode(2)
a_tree.right=TreeNode(3)
temp=a_tree.left
temp.left=TreeNode(4)
temp.right=TreeNode(5)
temp=a_tree.right
temp.left=TreeNode(6)
temp.right=TreeNode(7)
return a_tree
if __name__=='__main__':
a_tree=ProduceATree()
print 'PreOrder:'
PreOrder(a_tree,visit)
print 'InOrder:'
InOrder(a_tree,visit)
print 'PostOrder:'
PostOrder(a_tree,visit)
print 'LevelOrder:'
LevelOrder(a_tree,visit)
代码结果: