class Node(object):
"""结点"""
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
class BinaryTree(object):
"""二叉树"""
def __init__(self, node=None):
self.root = node
def is_empty(self):
"""判断是否为空树"""
return self.root is None
def add(self, item):
"""在树的最后添加结点"""
# 要添加的结点
node = Node(item)
# 空树
if self.root is None:
self.root = node
return
# 存放结点的队列, 从根结点开始
queue = [self.root]
while queue:
cur_node = queue.pop(0)
# 根结点的左孩子为空, 直接添加
if cur_node.lchild is None:
cur_node.lchild = node
return
# 根结点的左孩子不为空, 添加到结点队列
else:
queue.append(cur_node.lchild)
# 根结点的右孩子为空, 直接添加
if cur_node.rchild is None:
cur_node.rchild = node
return
# 根结点的右孩子不为空, 添加到结点队列
else:
queue.append(cur_node.rchild)
def breadth_travel(self):
"""广度优先遍历"""
if self.root is None:
return
# 存放树结点的队列
queue = [self.root]
# 左右孩子均不为空,不进队列, 只弹出结点, 队列为空时结束
while queue:
# 弹出当前结点
cur_node = queue.pop(0)
print(cur_node.data, end=" ")
# 左孩子不为空, 进队列
if cur_node.lchild is not None:
queue.append(cur_node.lchild)
# 右孩子不为空, 进队列
if cur_node.rchild is not None:
queue.append(cur_node.rchild)
def pre_order(self, node):
"""前序遍历, 根左右"""
if node is None:
return
print(node.data, end=" ")
self.pre_order(node.lchild)
self.pre_order(node.rchild)
def in_order(self, node):
"""中序遍历, 左根右"""
if node is None:
return
self.in_order(node.lchild)
print(node.data, end=" ")
self.in_order(node.rchild)
def post_order(self, node):
"""后序遍历, 左右根"""
if node is None:
return
self.post_order(node.lchild)
self.post_order(node.rchild)
print(node.data, end=" ")
if __name__ == '__main__':
tree = BinaryTree()
print(tree.is_empty())
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
tree.breadth_travel() # 0 1 2 3 4 5 6 7 8 9
print()
tree.pre_order(tree.root) # 0 1 3 7 8 4 9 2 5 6
print()
tree.in_order(tree.root) # 7 3 8 1 9 4 0 5 2 6
print()
tree.post_order(tree.root) # 7 8 3 9 4 1 5 6 2 0
print()