当前位置:网站首页>919. 完全二叉树插入器 : 简单 BFS 运用题
919. 完全二叉树插入器 : 简单 BFS 运用题
2022-07-25 11:31: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 原题链接和其他优选题解。
更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地
边栏推荐
- Eureka注册中心开启密码认证-记录
- 【AI4Code】《InferCode: Self-Supervised Learning of Code Representations by Predicting Subtrees》ICSE‘21
- mysql的表分区
- NLP的基本概念1
- 【RS采样】A Gain-Tuning Dynamic Negative Sampler for Recommendation (WWW 2022)
- Innovation and breakthrough! AsiaInfo technology helped a province of China Mobile complete the independent and controllable transformation of its core accounting database
- 客户端开放下载, 欢迎尝鲜
- 【GCN-RS】Are Graph Augmentations Necessary? Simple Graph Contrastive Learning for RS (SIGIR‘22)
- 知识图谱用于推荐系统问题(MVIN,KERL,CKAN,KRED,GAEAT)
- Transformer变体(Routing Transformer,Linformer,Big Bird)
猜你喜欢

【GCN-RS】MCL: Mixed-Centric Loss for Collaborative Filtering (WWW‘22)

Video caption (cross modal video summary / subtitle generation)

Intelligent information retrieval(智能信息检索综述)

【GCN-RS】MCL: Mixed-Centric Loss for Collaborative Filtering (WWW‘22)

Zuul网关使用

Eureka注册中心开启密码认证-记录

NLP的基本概念1

NLP知识----pytorch,反向传播,预测型任务的一些小碎块笔记

PHP curl post length required error setting header header

Application and innovation of low code technology in logistics management
随机推荐
Start with the development of wechat official account
【AI4Code】《CoSQA: 20,000+ Web Queries for Code Search and Question Answering》 ACL 2021
Heterogeneous graph neural network for recommendation system problems (ackrec, hfgn)
Location analysis of recording an online deadlock
Week303 of leetcode (20220724)
NLP的基本概念1
Eureka使用记录
通信总线协议一 :UART
Eureka注册中心开启密码认证-记录
2.1.2 机器学习的应用
Atomic atomic class
防范SYN洪泛攻击的方法 -- SYN cookie
【对比学习】Understanding the Behaviour of Contrastive Loss (CVPR‘21)
Application of comparative learning (lcgnn, videomoco, graphcl, XMC GaN)
R语言ggplot2可视化:使用ggpubr包的ggstripchart函数可视化点状条带图、设置palette参数配置不同水平数据点的颜色、设置add参数在点状条带图中添加均值标准差竖线
【微服务~Sentinel】Sentinel降级、限流、熔断
【AI4Code】《CodeBERT: A Pre-Trained Model for Programming and Natural Languages》 EMNLP 2020
给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享
R语言ggpubr包ggarrange函数将多幅图像组合起来、annotate_figure函数为组合图像添加注释、注解、标注信息、fig.lab参数添加图像标签、fig.lab.face参数指定样式
PHP curl post x-www-form-urlencoded