class Node(object):
def __init__(self, index):
self.index = index
self.left_child = None
self.right_child = None
class BinarySearchTree(object):
def __init__(self, root):
self.root = root
#前序遍历,根左右
def pre_travel(self, node):
if not node:
return
print(node.index)
self.pre_travel(node.left_child)
self.pre_travel(node.right_child)
#后序遍历,左右根
def post_travel(self, node):
if not node:
return
self.post_travel(node.left_child)
self.post_travel(node.right_child)
print(node.index)
#中序遍历,左根右
def in_travel(self, node):
if not node:
return
self.in_travel(node.left_child)
print(node.index)
self.in_travel(node.right_child)
node_dict = {}
for i in range(1, 11):
node_dict[i] = Node(i)
node_dict[1].left_child = node_dict[2]
node_dict[1].right_child = node_dict[3]
node_dict[2].left_child = node_dict[4]
node_dict[2].right_child = node_dict[5]
node_dict[3].left_child = node_dict[6]
node_dict[3].right_child = node_dict[7]
node_dict[4].left_child = node_dict[8]
node_dict[4].right_child = node_dict[9]
node_dict[5].left_child = node_dict[10]
tree = BinarySearchTree(node_dict[1])
print("\npre order travel:")
tree.pre_travel(tree.root)
print("\npost order travel:")
tree.post_travel(tree.root)
print("\nin order travel:")
tree.in_travel(tree.root)
生成的二叉树如下:
输出结果:
pre order travel:
1
2
4
8
9
5
10
3
6
7
post order travel:
8
9
4
10
5
2
6
7
3
1
in order travel:
8
4
9
2
10
5
1
6
3
7