LC 919. 完全二叉树插入器

题目描述

这是 LeetCode 上的 919. 完全二叉树插入器 ,难度为 中等

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

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

实现 CBTInserter 类:

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

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
输入
["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 $
  • 每个测试用例最多调用 insertget_root 操作 $10^4$ 次

BFS

起始使用数组对构造函数传入的 root 进行 BFS 层序遍历(由于仍要保留层序遍历顺序,因此使用下标指针 cur 来模拟出队位置)。

对于 insert 操作而言,我们要在数组(层序遍历顺序)中找到首个「存在左右空子节点」的父节点 fa,由于找到 fa 节点的过程数组下标单调递增,因此可以使用全局变量 idx 不断往后搜索,每次将新节点 node 添加到当前树后,需要将 node 添加到数组尾部。

get_root 操作则始终返回数组首位元素即可。

Java 代码:

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
class CBTInserter {
List<TreeNode> list = new ArrayList<>();
int idx = 0;
public CBTInserter(TreeNode root) {
list.add(root);
int cur = 0;
while (cur < list.size()) {
TreeNode node = list.get(cur);
if (node.left != null) list.add(node.left);
if (node.right != null) list.add(node.right);
cur++;
}
}
public int insert(int val) {
TreeNode node = new TreeNode(val);
while (list.get(idx).left != null && list.get(idx).right != null) idx++;
TreeNode fa = list.get(idx);
if (fa.left == null) fa.left = node;
else if (fa.right == null) fa.right = node;
list.add(node);
return fa.val;
}
public TreeNode get_root() {
return list.get(0);
}
}

TypeScript 代码:
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
class CBTInserter {
list: TreeNode[] = new Array<TreeNode>()
idx: number = 0
constructor(root: TreeNode | null) {
this.list.push(root)
let cur = 0
while (cur < this.list.length) {
const node = this.list[cur]
if (node.left != null) this.list.push(node.left)
if (node.right != null) this.list.push(node.right)
cur++
}
}
insert(val: number): number {
const node = new TreeNode(val)
while (this.list[this.idx].left != null && this.list[this.idx].right != null) this.idx++
const fa = this.list[this.idx]
if (fa.left == null) fa.left = node
else if (fa.right == null) fa.right = node
this.list.push(node)
return fa.val
}
get_root(): TreeNode | null {
return this.list[0]
}
}

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.919 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!