当前位置:网站首页>leetcode-919:完全二叉树插入器
leetcode-919:完全二叉树插入器
2022-07-25 20:36:00 【菊头蝙蝠】
leetcode-919:完全二叉树插入器
题目
完全二叉树 是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。
设计一种算法,将一个新节点插入到一个完整的二叉树中,并在插入后保持其完整。
实现 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]

解题
方法一:双队列—O(1)复杂度插入
如果每次插入的时候都进行层序遍历,那么如果在插入情况比较多的时候,效率会很低。
如果能直接从队列中取出节点,然后插入,那么就会快很多。
由于是完美二叉树,被插入的节点,只可能是2种状态
- 没有左、右子节点, 这种情况下后续是先插入左节点
- 有左子节点,没右子节点,这种情况下,插入右节点
初始化的时候将情况1,存储在q_L队列中,将情况2,存储在q_R队列中。
因此可以通过层序遍历,初始化q_L,q_R队列
由于完全二叉树的特性,插入的时候,优先从q_R队列中取值。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class CBTInserter {
public:
TreeNode* root;
queue<TreeNode*> q_L;//存放没有左右孩子的节点
queue<TreeNode*> q_R;//存放没有右孩子的节点
CBTInserter(TreeNode* root) {
//目的是为了初始化q_L和q_R队列
this->root=root;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* cur=q.front();
q.pop();
if(!cur->left&&!cur->right) q_L.push(cur);
if(cur->left&&!cur->right) q_R.push(cur);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
}
int insert(int val) {
if(!q_R.empty()){
//优先取仅没有右孩子的节点(因为完全二叉树的特点)
TreeNode* cur=q_R.front();
q_R.pop();
cur->right=new TreeNode(val);
q_L.push(cur->right);
return cur->val;
}
else{
//取没有左右孩子的节点
TreeNode* cur=q_L.front();
q_L.pop();
cur->left=new TreeNode(val);
q_R.push(cur);
q_L.push(cur->left);
return cur->val;
}
}
TreeNode* get_root() {
return root;
}
};
方法二:插入时–层序遍历
class CBTInserter {
public:
TreeNode* root;
CBTInserter(TreeNode* root) {
this->root=root;
}
int insert(int val) {
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode* cur=q.front();
q.pop();
if(cur->left) q.push(cur->left);
else{
cur->left=new TreeNode(val);
return cur->val;
}
if(cur->right) q.push(cur->right);
else{
cur->right=new TreeNode(val);
return cur->val;
}
}
return -1;
}
TreeNode* get_root() {
return root;
}
};
边栏推荐
- Increase swap space
- The uniapp project starts with an error binding Node is not a valid Win32 Application ultimate solution
- QML combines qsqltablemodel to dynamically load data MVC "recommended collection"
- Proxy implements MySQL read / write separation
- [cloud native] use of Nacos taskmanager task management
- 【高等数学】【6】多元函数微分学
- [today in history] July 7: release of C; Chrome OS came out; "Legend of swordsman" issued
- Volcanic engine Xiang Liang: machine learning and intelligent recommendation platform multi cloud deployment solution officially released
- Behind every piece of information you collect, you can't live without TA
- Socket error Event: 32 Error: 10053. Connection closing...Socket close
猜你喜欢

Kubernetes进阶部分学习笔记

Kubernetes advanced part learning notes
![[today in history] June 29: SGI and MIPS merged; Microsoft acquires PowerPoint developer; News corporation sells MySpace](/img/86/abeb82927803712a98d2018421c3a7.png)
[today in history] June 29: SGI and MIPS merged; Microsoft acquires PowerPoint developer; News corporation sells MySpace
![[advanced mathematics] [8] differential equation](/img/83/b6b07540e3cf6d6433e57447d42ee9.png)
[advanced mathematics] [8] differential equation
![[cloud native] use of Nacos taskmanager task management](/img/af/f1c5359e7dbcf51f02fa32839539b2.png)
[cloud native] use of Nacos taskmanager task management

增加 swap 空间
![[advanced mathematics] [1] function, limit, continuity](/img/c5/f9fd3814a61d0fba24b37253c7e51c.png)
[advanced mathematics] [1] function, limit, continuity

Volcanic engine Xiang Liang: machine learning and intelligent recommendation platform multi cloud deployment solution officially released

Solution to oom exceptions caused by improper use of multithreading in production environment (supreme Collection Edition)
![[today in history] July 5: the mother of Google was born; Two Turing Award pioneers born on the same day](/img/7d/7a01c8c6923077d6c201bf1ae02c8c.png)
[today in history] July 5: the mother of Google was born; Two Turing Award pioneers born on the same day
随机推荐
增加 swap 空间
What is cluster analysis? Categories of cluster analysis methods [easy to understand]
10. < tag dynamic programming and subsequence, subarray> lt.53. maximum subarray and + lt.392. Judge subsequence DBC
[today in history] June 30: von Neumann published the first draft; The semiconductor war in the late 1990s; CBS acquires CNET
[MCU] 51 MCU burning those things
4everland storage node portal network design
"Chain" connects infinite possibilities: digital asset chain, wonderful coming soon!
Dataframe first performs grouping operation and then combines output
智能电子界桩自然保护区远程监控解决方案
[onnx] export pytorch model to onnx format: support multi parameter and dynamic input
Step num problem
Volcanic engine Xiang Liang: machine learning and intelligent recommendation platform multi cloud deployment solution officially released
Formatdatetime explanation [easy to understand]
Arrow 之 Parquet
Timing analysis and constraints based on xlinx (1) -- what is timing analysis? What are temporal constraints? What is temporal convergence?
预处理指令
Interpretation of filter execution sequence source code in sprigboot
DIY个人服务器(diy存储服务器)
securecrt乱码解决方法[通俗易懂]
飞行器pid控制(旋翼飞控)