class TreeNode(object):
def __init__(self,left,right,data):
self.left = left
self.right = right
self.data = data
class BTree(object):
def init(self,root):
self.root = root
# 判空
def is_empty(self):
if self.root is None:
return True
return False
# 先序遍历
def pre_order(self,tree_node):
print tree_node.data
if tree_node.left is not None:
self.pre_order(tree_node.left)
if tree_node.right is not None:
self.pre_order(tree_node.right)
# 中序遍历
def in_order(self,tree_node):
if tree_node.left is not None:
self.in_order(tree_node.left)
print tree_node.data
if tree_node.right is not None:
self.in_order(tree_node.right)
# 后序遍历
def post_order(self,tree_node):
if tree_node.left is not None:
self.post_order(tree_node.left)
if tree_node.right is not None:
self.post_order(tree_node.right)
print tree_node.data
tree_d = TreeNode(left=None,right=None,data='D')
tree_e = TreeNode(left=None,data='E')
tree_f = TreeNode(left=None,data='F')
tree_b = TreeNode(left=tree_d,right=tree_e,data='B')
tree_c = TreeNode(left=tree_f,data='C')
tree_a = TreeNode(left=tree_b,right=tree_c,data='A')
下面是测试代码
btree = BTree(tree_a)
print btree.is_empty()
btree.pre_order(btree.root)
btree.in_order(btree.root)
btree.post_order(btree.root)
原文链接:https://www.f2er.com/note/421885.html