Python初始化二叉树的算法

Python初始化二叉树的算法

在数据结构的学习中, 二叉树的初始化是很常见的一种操作.
本文介绍一种基于队列, 从上到下从左到右的二叉树初始化方法.

# coding:utf-8
from queue import Queue


class BTNode:
    """二叉树结点类"""

    def __init__(self, data=None, l_child=None, r_child=None):
        self.data = data  # 数据域
        self.l_child = l_child  # 左孩子
        self.r_child = r_child  # 右孩子


def init_binary_tree(data):
    """
    初始化二叉树, 赋值顺序: 从上到下 从左到右
    """

    head_node = None
    current_node = None
    # 创建一个长度为100的队列 如果maxsize=-1为不限长度
    node_queue = Queue(maxsize=100)

    for item in data:
        # 创建新节点
        node = BTNode(item)

        # 如果头节点为空
        # 把头节点指向新节点
        # 把头节点设为当前节点
        if head_node is None:
            head_node = node
            current_node = head_node

        else:
            # 如果当前节点的左(右)孩子为空
            # 把当前节点左(右)孩子指向新节点
            # 把当前节点左(右)孩子入队列
            if current_node.l_child is None:
                current_node.l_child = node
                node_queue.put(current_node.l_child)
            elif current_node.r_child is None:
                current_node.r_child = node
                node_queue.put(current_node.r_child)

        # 如果当前节点左右孩子均不为空
        # 从队列中获取一个节点设为当前节点
        if current_node.l_child and current_node.r_child:
            current_node = node_queue.get()

    return head_node


if __name__ == '__main__':
    tree_data = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
    result = init_binary_tree(tree_data)
    print(result)

运行结果:
二叉树初始化结果

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值