# 二叉树的广度优先遍历
class Node(object):
def __init__(self, item):
self.elem = item
self.lchild = None
self.rchild = None
class Tree(object):
# 二叉树
def __init__(self):
self.root = None
def add(self, item):
# 广度优先使用队列实现,一边存,另一边取
node = Node(item)
if self.root is None:
self.root = node
return
# 构造队列时将根节点添加进来
queue = [self.root]
# print(queue)
# 队列不为空时,寻找待插入的位置
while queue:
# 从队列中读取当前节点
cur_node = queue.pop(0)
# print(cur_node)
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)
# print(queue)
def breadth_travel(self):
# 广度优先遍历
if self.root is None:
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
print(cur_node.elem, 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.elem, 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.elem, 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.elem, end=" ")
if __name__ == '__main__':
tree = Tree()
tree.add('A')
tree.add('B')
tree.add('C')
tree.add('D')
tree.add('E')
tree.add('F')
# 广度优先遍历
tree.breadth_travel()
print(" ")
# 前序遍历
node = Node('S')
# tree.pre_order(node)
tree.pre_order(tree.root)
print(" ")
# 中序遍历
tree.in_order(tree.root)
print(" ")
# 后序遍历
tree.post_order(tree.root)
print(" ")