当前位置:网站首页>919. 完全二叉树插入器 : 简单 BFS 运用题
919. 完全二叉树插入器 : 简单 BFS 运用题
2022-07-25 21:26:00 【宫水三叶的刷题日记】
题目描述
这是 LeetCode 上的 「919. 完全二叉树插入器」 ,难度为 「中等」。
Tag : 「模拟」、「BFS」、「树的遍历」
完全二叉树 是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。
设计一种算法,将一个新节点插入到一个完整的二叉树中,并在插入后保持其完整。
实现 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]
提示:
树中节点数量范围为 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 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 代码:
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 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。
更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地
本文由 mdnice 多平台发布
边栏推荐
- 基于腾讯地图实现精准定位,实现微信小程序考勤打卡功能
- C#程序设计的6大原则
- How to store pictures in the database "suggested collection"
- 作为测试,如何理解线程同步异步
- MySQL master-slave replication data synchronization, summary of common problems
- Too many passwords, don't know how to record? Why don't you write a password box applet yourself
- YUV422 to RGB (422sp to 420p)
- Pyqt5 use pyqtgraph to draw multiple y-value scatter plots
- Fusing and degrading Sentinel
- Opencv learning Fourier transform experience and line direction Fourier transform code
猜你喜欢

Pycharm跑程序时自动进入测试模式

Jmeter分布式压测

Debugged PEB (beingdebugged, ntglobalflag)

Cesium 多边形渐变色纹理(Canvas)

When facing complex problems, systematic thinking helps you understand the essence of the problem
![[ManageEngine] value brought by Siem to enterprises](/img/1e/56d64d193e0428523418bef5e98866.png)
[ManageEngine] value brought by Siem to enterprises

零基础学习CANoe Panel(17)—— Panel CAPL Function

浅谈web性能优化(一)

The onnx model is exported as a TRT model

Basic knowledge of Marine Geology
随机推荐
cuda_ error_ out_ of_ Memory (out of memory)
如何自动生成短链?如何在线批量生成带UTM参数的链接?
Interface testing tool restlet client
字节一面:TCP 和 UDP 可以使用同一个端口吗?
Achieve accurate positioning based on Tencent map, and realize the attendance punch function of wechat applet
Airtest解决“自动装包”过程中需要输入密码的问题(同适用于随机弹框处理)
seven point two three
Decompile app
An interview question about recover in golang
DDD go practice
cv图像翻转,EmguCV图像旋转「建议收藏」
CNN structural design skills: taking into account speed accuracy and engineering implementation
2022-07-18: what is the output of the following go language code? A:Groutine; B:Main; C:Goroutine; D:GoroutineMain。 package m
yuv422转rgb(422sp转420p)
Database SQL statement exercise "suggestions collection"
Autojs learning - realize 3D perspective
mysql导入数据时已改成csv utf8文件且文件名为英文,为什么还是导入失败
Oracle views the SQL statements with the slowest execution and the most queries
人脸与关键点检测:YOLO5Face实战
Vivo official website app full model UI adaptation scheme