919.完全二叉树插入器

完全二叉树插入器

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

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

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

示例 1:

输入:inputs = [“CBTInserter”,”insert”,”get_root”], inputs = [[[1,2,3,4,5,6]],[7],[]]
输出:[null,3,[1,2,3,4,5,6,7]]

示例 2:

输入:inputs = [“CBTInserter”,”insert”,”insert”,”get_root”], inputs = [[[1]],[2],[3],[]]
输出:[null,1,1,[1,2,3]]

提示:

  • 最初给定的树是完全二叉树,且包含 1 到 1000 个节点。
  • 每个测试用例最多调用 CBTInserter.insert 操作 10000 次。
  • 每个节点的值介于 1 和 5000 之间。

解析

使用队列存储所有有至少一个空子节点的节点,插入时从队首取节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var CBTInserter = function (root) {
this.root = root;
this.queue = [];
const q = [root];
while (q.length) {
const node = q.shift();
if (!node.left || !node.right) {
this.queue.push(node);
}
if (node.left) q.push(node.left);
if (node.right) q.push(node.right);
}
};

CBTInserter.prototype.insert = function (v) {
const node = new TreeNode(v);
const parent = this.queue[0];
if (!parent.left) {
parent.left = node;
} else {
parent.right = node;
this.queue.shift();
}
this.queue.push(node);
return parent.val;
};

CBTInserter.prototype.get_root = function () {
return this.root;
};

时间复杂度:初始化 O(n),insert O(1),get_root O(1)。空间复杂度 O(n)。


919.完全二叉树插入器
https://leetcode.lz5z.com/919.complete-binary-tree-inserter/
作者
tickli
发布于
2024年12月28日
许可协议