当前位置:网站首页>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 原题链接和其他优选题解。
更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地
边栏推荐
- NLP知识----pytorch,反向传播,预测型任务的一些小碎块笔记
- Transformer variants (routing transformer, linformer, big bird)
- 客户端开放下载, 欢迎尝鲜
- 【AI4Code】《Pythia: AI-assisted Code Completion System》(KDD 2019)
- web编程(二)CGI相关
- 通过Referer请求头实现防盗链
- Go garbage collector Guide
- NLP knowledge - pytorch, back propagation, some small pieces of notes for predictive tasks
- Week303 of leetcode (20220724)
- aaaaaaaaaaA heH heH nuN
猜你喜欢

【AI4Code】《Unified Pre-training for Program Understanding and Generation》 NAACL 2021

Learning to Pre-train Graph Neural Networks(图预训练与微调差异)

Those young people who left Netease

dirReader. Readentries compatibility issues. Exception error domexception

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

Learning to pre train graph neural networks

对比学习的应用(LCGNN,VideoMoCo,GraphCL,XMC-GAN)

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

OSPF综合实验

scrapy 爬虫框架简介
随机推荐
Hardware connection server TCP communication protocol gateway
Plus版SBOM:流水线物料清单PBOM
How to solve the problem of the error reported by the Flink SQL client when connecting to MySQL?
第一个scrapy爬虫
协程
JS interview question: handwriting throttle function
【微服务~Sentinel】Sentinel降级、限流、熔断
【AI4Code】《Unified Pre-training for Program Understanding and Generation》 NAACL 2021
LeetCode第303场周赛(20220724)
【6篇文章串讲ScalableGNN】围绕WWW 2022 best paper《PaSca》
Atomic atomic class
基于TCP/IP在同一局域网下的数据传输
Start with the development of wechat official account
【GCN-RS】MCL: Mixed-Centric Loss for Collaborative Filtering (WWW‘22)
Location analysis of recording an online deadlock
aaaaaaaaaaA heH heH nuN
氢能创业大赛 | 国家能源局科技司副司长刘亚芳:构建高质量创新体系是我国氢能产业发展的核心
投屏收费背后:爱奇艺季度盈利,优酷急了?
Power Bi -- these skills make the report more "compelling"“
【GCN-RS】MCL: Mixed-Centric Loss for Collaborative Filtering (WWW‘22)