LeetCode每日一题——919. 完全二叉树插入器

题目

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

设计一种算法,将一个新节点插入到一个完整的二叉树中,并在插入后保持其完整。

实现 CBTInserter 类:

CBTInserter(TreeNode root) 使用头节点为 root 的给定树初始化该数据结构;
CBTInserter.insert(int v) 向树中插入一个值为 Node.val == val的新节点 TreeNode。使树保持完全二叉树的状态,并返回插入节点 TreeNode 的父节点的值;
CBTInserter.get_root() 将返回树的头节点。

示例 1:

在这里插入图片描述

输入 [“CBTInserter”, “insert”, “insert”, “get_root”] [[[1, 2]], [3],[4], []]
输出 [null, 1, 2, [1, 2, 3, 4]]
解释 :CBTInserter cBTInserter = new CBTInserter([1, 2]);
cBTInserter.insert(3); // 返回 1 cBTInserter.insert(4); // 返回 2 cBTInserter.get_root(); // 返回 [1, 2, 3, 4]

提示:

树中节点数量范围为 [1, 1000]
0 <= Node.val <= 5000
root 是完全二叉树
0 <= val <= 5000
每个测试用例最多调用 insert 和 get_root 操作 104 次

思路

  1. 使用队列模拟,遍历二叉树的所有节点,发现左孩子或者右孩子为空的节点即记录,标记该节点。就是代码中get_temp()方法
  2. 初始化:记录根节点,以便get_root()方法直接返回, 调用get_temp()方法获得首个标记节点
  3. 将给定值插入到标记节点中,并重置该标记节点即可

题解


from collections import deque
class CBTInserter:
    # 初始化
    def __init__(self, root: TreeNode):
        self.root = root
        self.temp = self.get_temp(root)

    def insert(self, val: int) -> int:
        # 构造子节点,插入到标记节点中
        if self.temp.left:
            self.temp.right = TreeNode(val)
        else:
            self.temp.left = TreeNode(val)
        # 记录标记节点的值,在后面返回
        value = self.temp.val
        # 重置标记节点
        self.temp = self.get_temp(self.root)
        return value
    def get_root(self) -> TreeNode:
        return self.root
    # 寻找子节点为空的节点
    def get_temp(self, root):
        # 队列
        res = deque()
        res.append(root)
        while res:
            index = res.popleft()

            if index.left:
                res.append(index.left)
            # 左孩子为空,直接返回该节点
            else:
                return index
            if index.right:
                res.append(index.right)
            # 右孩子为空,直接返回该节点
            else:
                return index
        return None
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hyk今天写算法了吗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值