python数据结构与算法之二叉树
二叉树
上述图片案例的代码实现
# 定义节点
class BitreeNode:
def __init__(self, data):
self.data = data
self.lchild = None # 左孩子
self.rchild = None # 右孩子
a = BitreeNode('A')
b = BitreeNode('B')
c = BitreeNode('C')
d = BitreeNode('D')
e = BitreeNode('E')
f = BitreeNode('F')
g = BitreeNode('G')
e.lchild = a
e.rchild = g
a.rchild = c
c.lchild = b
c.rchild = d
g.rchild = f
root = e # 根节点
# 测试
print(root.lchild.rchild.data)
运行结果:
二叉树多种遍历方式:
代码实现:
print('前序遍历:')
pre_order(root)
print('\n')
# 中序遍历:先左后自己再右
def in_order(root):
if root:
in_order(root.lchild) # 访问左子树
print(root.data, end=' ') # 访问自己
in_order(root.rchild) # 访问右子树
print('中序遍历: ')
in_order(root)
print('\n')
# 后序遍历: 先左后右再自己
def post_order(root):
if root:
post_order(root.lchild)
post_order(root.rchild)
print(root.data, end=' ')
print('后序遍历: ')
post_order(root)
print('\n')
# 层次遍历
def level_order(root):
queue = deque() # 创建一个空队列
queue.append(root) # 添加root
while len(queue) > 0: # 只要队不空
node = queue.popleft() # 出队一个元素
print(node.data, end=' ')
if node.lchild: # 如果node左孩子存在
queue.append(node.lchild) # 左孩子添加进队
if node.rchild: # 如果右孩子存在
queue.append(node.rchild) # 有孩子添加进队
print('层次遍历: ')
level_order(root)
运行结果: