919. 完全二叉树插入器

题目
完全二叉树是每一层(除最后一层外)都是完全填充(即,结点数达到最大)的,并且所有的结点都尽可能地集中在左侧。

设计一个用完全二叉树初始化的数据结构 CBTInserter,它支持以下几种操作:

  1. CBTInserter(TreeNode root) 使用头结点为 root 的给定树初始化该数据结构;
  2. CBTInserter.insert(int v) 将 TreeNode 插入到存在值为 node.val = v 的树中以使其保持完全二叉树的状态,并返回插入的 TreeNode 的父结点的值;
  3. CBTInserter.get_root() 将返回树的头结点。

【中等】
【分析】使用列表来装树的父结点,如此既可以实现完全二叉树的数组形式(即可以O(1)定位到要插入结点的父结点,实现快速插入)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class CBTInserter:    
    def __init__(self, root: TreeNode):
        nodes=[root]
        self.CBT=[]  #既可以得到数组的形式,又可以保留树结构;有点耗费空间,但是也便于insert操作
        while nodes:
            node=nodes.pop(0)
            self.CBT.append(node)
            if node.left:
                nodes.append(node.left)                   
            if node.right:
                nodes.append(node.right)

    def insert(self, v: int) -> int:
        import math
        parent=math.floor((len(self.CBT)-1)/2)
        if self.CBT[parent].left:
            print("left")
            self.CBT[parent].right=TreeNode(v)
            self.CBT.append(self.CBT[parent].right)
        else:
            self.CBT[parent].left=TreeNode(v)
            self.CBT.append(self.CBT[parent].left)
        return self.CBT[parent].val       

    def get_root(self) -> TreeNode:
        return self.CBT[0]


# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()

在这里插入图片描述
时长上较长,以后再看是否有改进。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值