2 Star 0 Fork 0

xinanXu/myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LC919.cpp 2.38 KB
一键复制 编辑 原始数据 按行查看 历史
xinanXu 提交于 2023-03-01 17:48 . 919. 完全二叉树插入器
/**
* 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*> par;
queue<TreeNode*> now;
CBTInserter(TreeNode* root) {
this->root = root;
if (!root) return;
if (root && !root->left) {
now.push(root);
return;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
unsigned int len = q.size();
par = q;
queue<TreeNode*> t;
while (!q.empty()) {
auto node = q.front();
if (node->left) t.push(node->left);
if (node->right) t.push(node->right);
q.pop();
}
q = t;
if (!t.empty() && t.size() != len * 2)
now = par;
}
if (now.empty()) {
now = par;
return;
}
par = now;
while (!par.empty()) {
if (par.front() && par.front()->left) now.push(par.front()->left);
if (par.front() && par.front()->right) now.push(par.front()->right);
par.pop();
}
while (1) {
auto node = now.front();
if (node->left && node->right) {
printf("%d %d\n", node->left->val, node->right->val);
now.pop();
}
else break;
}
}
int insert(int val) {
TreeNode* node = new TreeNode(val);
auto n = now.front();
if (!n->left) {
printf("%d\n", n->val);
n->left = node;
}
else if (!n->right) {
printf("%d\n", n->val);
n->right = node;
now.pop();
}
now.push(node);
return n->val;
}
TreeNode* get_root() {
return root;
}
};
/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter* obj = new CBTInserter(root);
* int param_1 = obj->insert(val);
* TreeNode* param_2 = obj->get_root();
*/
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/DearAtri/myleetcode.git
git@gitee.com:DearAtri/myleetcode.git
DearAtri
myleetcode
myleetcode
master

搜索帮助