C++完整二叉树插入器
众所周知,完整二叉树是指除最后一层外,每一层都被完全填满,并且所有节点都尽可能靠左的二叉树。我们必须编写一个名为CBTInserter的数据结构,它用一个完整的二叉树初始化,并支持以下操作:
CBTInserter(TreeNode root):这将用给定的根节点root初始化数据结构;
CBTInserter.insert(int v):用于将一个值为node.val = v的TreeNode插入到树中,使得树保持完整,并返回插入的TreeNode的父节点的值;
CBTInserter.get_root():这将返回树的根节点。
例如,如果我们将树初始化为[1,2,3,4,5,6],然后插入7和8,然后尝试获取树,输出将是:3, 4,[1,2,3,4,5,6,7,8],3是因为7将插入到3下,4是因为8将插入到4下。
为了解决这个问题,我们将遵循以下步骤:
定义一个队列q和一个根节点
初始化器将获取完整的二叉树,然后按如下方式工作:
将root设置为给定的root,并将root插入到q中。
while循环:
如果root的左子节点存在,则将root的左子节点插入到q中,否则中断循环。
如果root的右子节点存在,则将root的右子节点插入到q中,并从q中删除首节点,否则中断循环。
在insert方法中,它将获取值v。
设置parent := q的首元素,temp := 一个值为v的新节点,并将temp插入到q中。
如果parent的左子节点不存在,则设置parent的左子节点 := temp;否则,从q中删除首元素,并将temp作为parent的右子节点插入。
返回parent的值。
在getRoot()方法中,返回root。
示例(C++)
让我们看看下面的实现来更好地理解:
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
} else {
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
} else {
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
} else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr == NULL || curr->val == 0){
cout << "null" << ", ";
} else{
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class CBTInserter {
public:
queue <TreeNode*> q;
TreeNode* root;
CBTInserter(TreeNode* root) {
this->root = root;
q.push(root);
while(1){
if(root->left){
q.push(root->left);
}
else break;
if(root->right){
q.push(root->right);
q.pop();
root = q.front();
}
else break;
}
}
int insert(int v) {
TreeNode* parent = q.front();
TreeNode* temp = new TreeNode(v);
q.push(temp);
if(!parent->left){
parent->left = temp;
} else {
q.pop();
parent->right = temp;
}
return parent->val;
}
TreeNode* get_root() {
return root;
}
};
main(){
vector<int> v = {1,2,3,4,5,6};
TreeNode *root = make_tree(v);
CBTInserter ob(root);
cout << (ob.insert(7)) << endl;
cout << (ob.insert(8)) << endl;
tree_level_trav(ob.get_root());
}输入
Initialize the tree as [1,2,3,4,5,6], then insert 7 and 8 into the tree, then find root
输出
3 4 [1, 2, 3, 4, 5, 6, 7, 8, ]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP