当前位置:网站首页>919. Complete binary tree inserter: simple BFS application problem
919. Complete binary tree inserter: simple BFS application problem
2022-07-25 12:16:00 【Gong Shui Sanye's Diary of writing questions】
Title Description
This is a LeetCode Upper 「919. Complete binary tree inserter 」 , The difficulty is 「 secondary 」.
Tag : 「 simulation 」、「BFS」、「 Tree traversal 」
Perfect binary tree Every floor ( Except for the last floor ) All completely filled ( namely , The number of nodes reaches the maximum ) Of , And all nodes are concentrated on the left as much as possible .
Design an algorithm , Insert a new node into a complete binary tree , And keep it intact after insertion .
Realization CBTInserter class :
CBTInserter(TreeNode root)Use the header node asrootInitialize the data structure for the given tree ;CBTInserter.insert(int v)Insert a value of... Into the treeNode.val == valThe new nodeTreeNode. Keep the tree in the state of a complete binary tree , And return to the insert nodeTreeNodeThe value of the parent node ofCBTInserter.get_root()The head node of the tree will be returned .
Example 1: 
Input
["CBTInserter", "insert", "insert", "get_root"]
[[[1, 2]], [3], [4], []]
Output
[null, 1, 2, [1, 2, 3, 4]]
explain
CBTInserter cBTInserter = new CBTInserter([1, 2]);
cBTInserter.insert(3); // return 1
cBTInserter.insert(4); // return 2
cBTInserter.get_root(); // return [1, 2, 3, 4]
Tips :
The number of nodes in the tree ranges from rootIt's a perfect binary treeEach test case calls at most insertandget_rootoperation Time
BFS
Start with the array passed into the constructor root Conduct BFS Sequence traversal ( Because the sequence traversal order still needs to be preserved , So use a subscript pointer cur To simulate the out of line position ).
about insert In terms of operation , We're going to be in the array ( Sequence traversal sequence ) First found in 「 There are left and right empty child nodes 」 Parent node fa, By finding fa The subscript of the process array of nodes increases monotonically , So you can use global variables idx Keep searching back , Every time a new node node Add to the current tree , Need to put node Add to end of array .
get_root Operation always returns the first element of the array .
Java Code :
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 Code :
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]
}
}
Time complexity : Spatial complexity :
Last
This is us. 「 Brush through LeetCode」 The first of the series No.919 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
More, more, more popular 「 written examination / interview 」 Relevant information can be found in the beautifully arranged Gather new bases
边栏推荐
- Eureka registration center opens password authentication - record
- R language Visual scatter diagram, geom using ggrep package_ text_ The rep function avoids overlapping labels between data points (set the min.segment.length parameter to inf and do not add label segm
- MySQL练习二
- Feign使用
- Unexpected rollback exception analysis and transaction propagation strategy for nested transactions
- [untitled]
- 【GCN-RS】MCL: Mixed-Centric Loss for Collaborative Filtering (WWW‘22)
- monit安装和使用
- 容错机制记录
- 【GCN-RS】Are Graph Augmentations Necessary? Simple Graph Contrastive Learning for RS (SIGIR‘22)
猜你喜欢

GPT plus money (OpenAI CLIP,DALL-E)

给生活加点惊喜,做创意生活的原型设计师丨编程挑战赛 x 选手分享

从云原生到智能化,深度解读行业首个「视频直播技术最佳实践图谱」

防范SYN洪泛攻击的方法 -- SYN cookie

氢能创业大赛 | 国家能源局科技司副司长刘亚芳:构建高质量创新体系是我国氢能产业发展的核心

Transformer variants (spark transformer, longformer, switch transformer)

【GCN-RS】Region or Global? A Principle for Negative Sampling in Graph-based Recommendation (TKDE‘22)

嵌套事务 UnexpectedRollbackException 分析与事务传播策略

Hydrogen entrepreneurship competition | Liu Yafang, deputy director of the science and Technology Department of the National Energy Administration: building a high-quality innovation system is the cor

【AI4Code】《Pythia: AI-assisted Code Completion System》(KDD 2019)
随机推荐
Scott+scott law firm plans to file a class action against Yuga labs, or will confirm whether NFT is a securities product
Behind the screen projection charge: iqiyi's quarterly profit, is Youku in a hurry?
【RS采样】A Gain-Tuning Dynamic Negative Sampler for Recommendation (WWW 2022)
Implement anti-theft chain through referer request header
对比学习的应用(LCGNN,VideoMoCo,GraphCL,XMC-GAN)
I advise those students who have just joined the work: if you want to enter the big factory, you must master these concurrent programming knowledge! Complete learning route!! (recommended Collection)
氢能创业大赛 | 国家能源局科技司副司长刘亚芳:构建高质量创新体系是我国氢能产业发展的核心
防范SYN洪泛攻击的方法 -- SYN cookie
MySQL练习二
keepalived实现mysql的高可用
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置add参数在小提琴内部添加抖动数据点以及均值标准差竖线(jitter and mean_sd)
【GCN-RS】Are Graph Augmentations Necessary? Simple Graph Contrastive Learning for RS (SIGIR‘22)
R语言可视化散点图、使用ggrepel包的geom_text_repel函数避免数据点之间的标签互相重叠(设置min.segment.length参数为Inf不添加标签线段)
Sword finger offer 22. the penultimate node in the linked list
[multimodal] hit: hierarchical transformer with momentum contract for video text retrieval iccv 2021
OSPF comprehensive experiment
Video caption (cross modal video summary / subtitle generation)
3.2.1 什么是机器学习?
'C:\xampp\php\ext\php_ zip. Dll'-%1 is not a valid Win32 Application Solution
【GCN多模态RS】《Pre-training Representations of Multi-modal Multi-query E-commerce Search》 KDD 2022