12.python实现顺序存储二叉树

顺序存储二叉树是指用一个数组存储的二叉树,一般用于完全二叉树,物理上用数组存储逻辑上是一个树结构。

  • 第n个元素的左节点索引2n+1
  • 第n个元素的右节点索引2n+2
  • 第n个元素的父节点为(n-1)/2
  • n为元素在数组中的索引
class Node(object):
    def __init__(self, data):
        self.data = data


class ArrayBinaryTree(object):
    """
    顺序存储二叉树是指用一个数组存储的二叉树,一般用于完全二叉树,物理上用数组存储逻辑上是一个树结构。
    顺序存储二叉树 基于数组实现
    左节点 2n+1
    右节点 2n+2
    父节点 (n-1)/2
    """

    def __init__(self, nodes=[]):
        self.nodes = nodes

    def pre_order(self, index):
        """
        前序遍历
        :return:
        """
        length = len(self.nodes)
        if length <= 0 or index > length:
            raise Exception("tree is empty or index out of range!")
        print(self.nodes[index].data, end='->')
        left_index = 2 * index + 1
        if left_index < length and self.nodes[left_index] is not None:
            self.pre_order(left_index)
        right_index = 2 * index + 2
        if right_index < length and self.nodes[right_index] is not None:
            self.pre_order(right_index)

    def in_order(self, index):
        """
        中序遍历
        :param index:
        :return:
        """
        length = len(self.nodes)
        left_index = 2 * index + 1
        if left_index < length and self.nodes[left_index] is not None:
            self.in_order(left_index)
        print(self.nodes[index].data, end='->')
        right_index = 2 * index + 2
        if right_index < length and self.nodes[right_index] is not None:
            self.in_order(right_index)

    def post_order(self, index):
        """
        后序遍历
        :param index:
        :return:
        """
        length = len(self.nodes)
        left_index = 2 * index + 1
        if left_index < length and self.nodes[left_index] is not None:
            self.post_order(left_index)
        right_index = 2 * index + 2
        if right_index < length and self.nodes[right_index] is not None:
            self.post_order(right_index)
        print(self.nodes[index].data, end='->')


if __name__ == '__main__':
    array_binary_tree = ArrayBinaryTree([Node(i) for i in range(1, 8)])
    array_binary_tree.pre_order(0)
    print()
    array_binary_tree.in_order(0)
    print()
    array_binary_tree.post_order(0)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值