当前位置:网站首页>Illustration leetcode - 919. Complete binary tree inserter (difficulty: medium)
Illustration leetcode - 919. Complete binary tree inserter (difficulty: medium)
2022-07-25 08:49:00 【Javanese Muse】
One 、 subject
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 of ;CBTInserter.get_root()The head node of the tree will be returned .
Two 、 Example
2.1> 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
[1, 1000]0 <= Node.val <= 5000rootIt's a perfect binary tree0 <= val <= 5000- Each test case calls at most
insertandget_rootoperation10^4Time
3、 ... and 、 Their thinking
3.1> breadth-first + queue
First , According to the title requirements , First add data according to each layer , In the same layer , Add nodes from left to right . Then we can go through the queue (queue) To execute Breadth first traversal Nodes of each layer , In the process of traversing , then Left node is empty perhaps The right node is empty The node of , Put into another queue (queueInsertNode) in , For subsequent insert operation . As shown in the figure below :

When we need to insert new nodes , First , Put the created new node into queueInsertNode In line , Used for the subsequent addition of new nodes . secondly , By calling peek() Method to get the queue header element , But this element will not be deleted from the queue . After getting the header element , Put the new node on the left or right side of the node , If it is placed on the right , It means that the left and right leaf nodes of the header element already exist , Then call poll() Method to set the element “ Kicked out ” queue . The specific operation is shown in the figure below :

Four 、 Code implementation
4.1> breadth-first + queue
public class CBTInserter {
private Queue<TreeNode> queueInsertNode;
private TreeNode root;
public CBTInserter(TreeNode root) {
this.root = root;
Queue<TreeNode> queue = new ArrayDeque<>();
queueInsertNode = new ArrayDeque<>();
queue.offer(root);
TreeNode node;
while (!queue.isEmpty()) { // Breadth first traversal
node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
if (node.left == null || node.right == null) {
queueInsertNode.offer(node);
}
}
}
public int insert(int val) {
TreeNode newNode = new TreeNode(val);
TreeNode node = queueInsertNode.peek();
if (node.left == null) {
node.left = newNode;
} else if (node.right == null) {
node.right = newNode;
queueInsertNode.poll();
}
queueInsertNode.offer(newNode);
return node.val;
}
public TreeNode get_root() {
return root;
}
}
That's all for today's article :
Writing is not easy to , An article completed by the author in hours or even days , I only want to exchange you for a few seconds give the thumbs-up & Share .
More technical dry goods , Welcome everyone to follow the official account @ Java Muse 「 Dry cargo sharing , Update daily 」
Previous recommendation
The illustration LeetCode——731. My schedule II( difficulty : secondary )
https://mp.csdn.net/mp_blog/creation/editor/125884328 The illustration LeetCode——3. Longest substring without repeating characters ( difficulty : secondary )
https://mp.csdn.net/mp_blog/creation/editor/125857066LeetCode Work: ——21. Merge two ordered lists ( difficulty : Simple )
https://mp.csdn.net/mp_blog/creation/editor/125840103LeetCode Work: ——565. Array nesting ( difficulty : secondary )
https://mp.csdn.net/mp_blog/creation/editor/125831251
Title source : Power button (LeetCode)
边栏推荐
- FreeMaker模板引擎
- 本周大新闻|FCC曝光Pico 4 VR一体机,雷朋母公司建立智能眼镜实验室
- Freemaker template engine
- SSM+JSP+MYSQL实现的宠物领养收养管理系统源码
- Apartment repair reporting system (idea, SSM, MySQL)
- OpenGL es to realize the visualization of real-time audio
- 英特尔就产品延误向Xe HPG寻宝游戏获奖者道歉并公布奖品样貌
- Tips for improving code sustainability, take connectto method as an example.
- YOLOV5环境配置
- Initial knowledge of WebService (generate jar packages and call methods in remote services)
猜你喜欢

CIR industrial automation radar

技术面②Mysql中的索引(index)类型有哪些并简要介绍一下?什么时候需要创建索引?什么时候不需要创建索引?为什么创建索引后查询速度会提高?

Wechat reservation of small program completion works (5) assignment book of small program graduation project

华为设备远程登录(Telnet、SSH)配置

Does the server operation and maintenance need to be online 24 hours? Do you need to work overtime on weekends?

Wechat sports ground reservation applet graduation design of applet completion works (2) applet function

@The difference and use of value and configurationproperties

Arcgis10.2 installation tutorial

Source code of pet adoption management system implemented by ssm+jsp+mysql

(self drawn ugly picture) simple understanding tcp/ip three handshakes and four waves
随机推荐
canvas很多圆圈组成的文本js特效
51单片机内部外设:串口通信
The fifth day of MATLAB learning (cycle type)
efcore在Saas系统下多租户零脚本分表分库读写分离解决方案
ip命令使用详解
为什么要使用MQ消息中间件?这几个问题必须拿下!
Wechat reservation of small program completion works (5) assignment book of small program graduation project
Foundation 32: page element positioning method XPath --- axis positioning method
A page widgetization practice
Redis学习笔记
Unity client reading text configuration
51 MCU internal peripherals: timer and counter
OpenGL es to achieve the effect of "big head, small head" and "head shaking"
uni-app
CIR industrial automation radar
防抖与节流
Review the second time, 220614, video, day03_ Data warehouse design,
flink sql怎么持久化?
51 MCU internal peripherals: serial port communication
Talk about your transformation test development process