우리가 알고 있듯이 완전한 이진 트리는 가능한 마지막을 제외한 모든 수준이 완전히 채워지고 모든 노드가 가능한 한 왼쪽에 있는 이진 트리입니다. 완전한 이진 트리로 초기화되고 다음 작업을 지원하는 데이터 구조 CBTInserter를 작성해야 합니다.
-
CBTInserter(TreeNode 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은 3 아래에 7이 삽입되기 때문이고 4는 4 아래에 8이 삽입되기 때문입니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
큐 q 및 루트 정의
-
이니셜라이저는 전체 이진 트리를 사용하고 다음과 같이 작동합니다.
-
루트를 주어진 루트로 설정하고 루트를 q
에 삽입합니다. -
사실일 때 -
-
루트의 왼쪽이 있으면 루트의 왼쪽을 q에 삽입하고, 그렇지 않으면 루프를 끊습니다.
-
루트의 오른쪽이 있으면 루트의 오른쪽을 q에 삽입하고 q에서 앞 노드를 삭제합니다. 그렇지 않으면 루프를 끊습니다.
-
-
삽입 방법에서 v
값을 취합니다. -
set parent :=q의 앞 요소, temp :=값이 v인 새 노드를 설정하고 q
에 삽입합니다. -
부모의 왼쪽이 없으면 부모의 왼쪽으로 설정 :=temp 그렇지 않으면 q에서 앞 요소를 삭제하고 temp를 부모의 오른쪽 자식으로 삽입
-
부모의 값을 반환
-
getRoot() 메서드에서 루트를 반환
예(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, ]