0
点赞
收藏
分享

微信扫一扫

919. 完全二叉树插入器 : 简单 BFS 运用题

题目描述

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

Tag : 「模拟」、「BFS」、「树的遍历」

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

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

实现 ​​CBTInserter​​ 类:

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

示例 1:

919. 完全二叉树插入器 : 简单 BFS 运用题_完全二叉树

输入
["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]

提示:

  • 树中节点数量范围为
  • ​root​​ 是完全二叉树
  • 每个测试用例最多调用​​insert​​​ 和​​get_root​​​ 操作

BFS

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

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

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

Java 代码:

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 {
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 代码:

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]
}
}

  • 时间复杂度:
  • 空间复杂度:

最后

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

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

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


举报

相关推荐

搜索二叉树、完全二叉树

0 条评论