二叉树 @ Python
class TreeNode(object):
def __init__(self):
self.data = '#'
self.left_child = None
self.right_child = None
class Tree(object):
def create_tree(self, treeNode):
data = raw_input('->')
if data == '#':
treeNode = TreeNode()
else:
treeNode.data = data
treeNode.left_child = TreeNode()
treeNode.right_child = TreeNode()
self.create_tree(treeNode.left_child)
self.create_tree(treeNode.right_child)
def visit(self, tree):
if not tree.data == '#':
print tree.data
def pre_order(self, tree):
if not tree.data == '#':
self.visit(tree)
self.visit(tree.left_child)
self.visit(tree.right_child)
def in_order(self, tree):
if not tree.data == '#':
self.visit(tree.left_child)
self.visit(tree)
self.visit(tree.right_child)
def post_order(self, tree):
if not tree.data == '#':
self.visit(tree.left_child)
self.visit(tree.right_child)
self.visit(tree)
def main():
"""Example usage"""
t = TreeNode()
tree = Tree()
tree.create_tree(t)
tree.pre_order(t)
print
tree.in_order(t)
print
tree.post_order(t)
if __name__ == '__main__':
main()