python数据结构与算法之二叉树

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)

运行结果:
在这里插入图片描述

二叉搜索树

在这里插入图片描述

参考视频:清华计算机博士带你学习python算法+数据结构

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SimpleZihao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值