代码如下:
class BinaryTree(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def preOrder(self, node):
if node is None:
return
print node.data
self.preOrder(node.left)
self.preOrder(node.right)
def midOrder(self, node):
if node is None:
return
self.midOrder(node.left)
print node.data
self.midOrder(node.right)
def postOrder(self, node):
if node is None:
return
self.postOrder(node.left)
self.postOrder(node.right)
print node.data
if __name__ == "__main__":
node = BinaryTree
bt = node('D',node('B',node('A'),node('C')),node('E',right=node('G',node('F'))))
print "pre order"
bt.preOrder(bt)
print "mid order"
bt.midOrder(bt)
print "post order"
bt.postOrder(bt)
或者将写两个类,一个专门用来实例化二叉树,另一个是遍历二叉树的类。
#-*- encoding:utf-8 -*-
class BinaryTreeNode(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BinaryTree(object):
def preOrder(self, node):
if node is None:
return
print node.data
self.preOrder(node.left)
self.preOrder(node.right)
def midOrder(self, node):
if node is None:
return
self.midOrder(node.left)
print node.data
self.midOrder(node.right)
def postOrder(self, node):
if node is None:
return
self.postOrder(node.left)
self.postOrder(node.right)
print node.data
if __name__ == "__main__":
node = BinaryTreeNode
root = node('D',node('B',node('A'),node('C')),node('E',right=node('G',node('F'))))
bt = BinaryTree()
print "+++++++++ pre order +++++++++++"
bt.preOrder(root)
print "+++++++++ mid order +++++++++++"
bt.midOrder(root)
print "+++++++++ post order +++++++++++"
bt.postOrder(root)
网友评论