代码拉取完成,页面将自动刷新
/**
* 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();
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。