当前位置:网站首页>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)
边栏推荐
- Yolov5 environment configuration
- Record the process of two multi terminal troubleshooting
- Foundation 31: Selenium positioning dynamic ID element
- 【芝麻街一家】& Bert Bart RoBERTa
- @Autowired注解的实现原理
- Redis learning notes
- table表格展开内部行切换效果
- Solutions to ten questions of leetcode database
- BigDecimel转人民币大写
- Qt|QLable多行展示时更改行间距
猜你喜欢

这是我见过写得最烂的Controller层代码...

LeetCode·83双周赛·6129.全0子数组的数目·数学
![[ten thousand words long text] Based on LSM tree thought Net 6.0 C # realize kV database (case version)](/img/07/235785b7658b5ae022dfa3f53ec86d.png)
[ten thousand words long text] Based on LSM tree thought Net 6.0 C # realize kV database (case version)

uni-app

51 MCU peripherals: buzzer

Graduation design of wechat small program ordering system of small program completion works (5) assignment
![[hero planet July training leetcode problem solving daily] 19th binary tree](/img/16/d4beab998f00e09bb45c64673bb2c8.png)
[hero planet July training leetcode problem solving daily] 19th binary tree

25 Ph.D. degrees revoked

FreeMaker模板引擎

QA robot sequencing model
随机推荐
sticksy.js页面滚动div固定位置插件
PHP reports an error: classes\phpexcel\cell php Line(594) Invalid cell coordinate ESIGN1
Tips for improving code sustainability, take connectto method as an example.
serialization and deserialization
防抖与节流
Talk about your transformation test development process
NVIDIA programmable reasoning accelerator tensorrt learning notes (II) - practical operation
Practice of establishing dynamic programming state transition equation
Swift初始化器及可选链
哈希表刷题(上)
efcore在Saas系统下多租户零脚本分表分库读写分离解决方案
Django4.0 + Web + MySQL5.7 实现简单登录操作
read
Dependency conflict resolution under idea
本周大新闻|FCC曝光Pico 4 VR一体机,雷朋母公司建立智能眼镜实验室
When crontab scheduled task executes jar through script, it encounters a pit where jar package execution is invalid
uni-app
Graduation design of wechat small program ordering system of small program completion works (3) background function
Leetcode · 83 biweekly race · 6129. Number of all 0 subarrays · mathematics
Network solutions for Alibaba cloud services