# 定义一个类 创建一个二叉树
class Btree:
def __init__(self,data):
self.data = data
self.lchild = None
self.rchild = None
a = Btree("A")
b = Btree("B")
c = Btree("C")
d = Btree("D")
e = Btree("E")
f = Btree("F")
root = a
a.lchild = b
a.rchild = c
b.lchild = d
b.rchild = e
c.lchild = f
# 广度优先遍历
def level_order(root):
if not root or root.data is None:
return []
else:
my_queue=[]
re_queue=[]
my_queue.append(root)
while my_queue:
cur_node = my_queue.pop(0)
re_queue.append(cur_node.data)
if cur_node.lchild:
my_queue.append(cur_node.lchild)
if cur_node.rchild:
my_queue.append(cur_node.rchild)
return re_queue
level_order(root) # ['A', 'B', 'C', 'D', 'E', 'F']
# 前序遍历
def pre_order(root):
if root:
print(root.data, end=" ")
pre_order(root.lchild)
pre_order(root.rchild)
pre_order(root)
# A B D E C F
# 中序遍历
# 每次从左孩子返回 打印该节点
# 先递归左孩子,再输出自己,再递归右孩子. 意味着只有当每一个节点的左孩子全部打印,再打印自己,最后打印右孩子
def mid_order(root):
if root:
mid_order(root.lchild)
print(root.data,end=" ")
mid_order(root.rchild)
mid_order(root)
# D B E A F C
# 后序遍历
# 先递归左子树,在递归右子树,最后输出节点自己. (左子树,右子树,节点)
def post_order(root):
if root:
post_order(root.lchild)
post_order(root.rchild)
print(root.data,end=" ")
post_order(root)
# D E B F C A