当前位置:网站首页>919. Complete binary tree inserter: simple BFS application problem
919. Complete binary tree inserter: simple BFS application problem
2022-07-25 21:29: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
This paper is written by mdnice Multi platform Publishing
边栏推荐
- Leetcode skimming -- guess the size of numbers II 375 medium
- The role of the resize function is "suggestions collection"
- Beisen Holdings' IPO: a total loss of 4.115 billion yuan in three years, and a total of 2.84 billion yuan in the previous nine rounds of financing
- 有哪些优化mysql索引的方式请举例(sqlserver索引优化)
- Jmeter分布式压测
- How to solve the problem of high concurrency and large traffic with PHP
- Interviewer of large factory: how to quickly query a table with tens of millions of data?
- On Web Performance Optimization (1)
- resize函数的作用「建议收藏」
- The inexplicability of Intel disassembly
猜你喜欢

Pychart automatically enters the test mode when running the program

Reading the pointpillar code of openpcdet -- Part 3: Calculation of loss function

ag 搜索工具参数详解

SSH private key realizes login to remote target server

Test cases and defect report templates

Detailed explanation of Ag search tool parameters

The adequacy of source evaluation forum · observation model test
What's special about Huawei's innovative solutions to consolidate the foundation of ERP for small and medium-sized enterprises?

Canvas fill gradient

函数栈帧的创建和销毁
随机推荐
Fusing and degrading Sentinel
Huatai Securities account opening process, is it safe to open an account on your mobile phone
Zero basic learning canoe panel (17) -- panel CAPL function
Debugged PEB (beingdebugged, ntglobalflag)
How to solve the problem of high concurrency and large traffic with PHP
Intel base instruction -- bnd
Database SQL statement exercise "suggestions collection"
如何自动生成短链?如何在线批量生成带UTM参数的链接?
NPM module removal_ [solved] after NPM uninstalls the module, the module is not removed from package.json [easy to understand]
Vivo official website app full model UI adaptation scheme
Apple estimates that iPhone will give up the Chinese market, and the Chinese industrial chain needs to consider living a hard life
字节一面:TCP 和 UDP 可以使用同一个端口吗?
CNN structural design skills: taking into account speed accuracy and engineering implementation
DDD go practice
My heart's broken! After being cheated by 30000, a 16-year-old girl was unconvinced and cheated by 50000
When facing complex problems, systematic thinking helps you understand the essence of the problem
Six principles of C program design
开源协议是否具有法律效力?
zigbee物联网开发平台(工业物联网)
Airtest solves the problem that a password needs to be entered in the process of "automatic packaging" (the same applies to random bullet frame processing)