Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++로 구현하는 완전 이진 트리 삽입기(CBTInserter)

완전 이진 트리 삽입기란?

완전 이진 트리(Complete Binary Tree)는 마지막 레벨을 제외한 모든 레벨이 가득 차 있고, 노드들이 최대한 왼쪽으로 치우쳐 배치된 이진 트리입니다. 이 문제에서는 주어진 완전 이진 트리로 초기화되는 CBTInserter라는 자료구조를 작성해야 하며, 다음 세 가지 연산을 지원해야 합니다.

  • CBTInserter(TreeNode root) : 루트 노드가 주어진 트리로 자료구조를 초기화합니다.
  • CBTInserter.insert(int v) : node.val = v인 새 TreeNode를 트리에 삽입하여 트리가 계속 완전 이진 트리 상태를 유지하도록 하고, 삽입된 노드의 부모 노드 값을 반환합니다.
  • CBTInserter.get_root() : 트리의 루트(헤드) 노드를 반환합니다.

동작 예시

예를 들어 트리를 [1,2,3,4,5,6]으로 초기화한 뒤 7과 8을 차례로 삽입하고 트리를 조회하면, 출력은 3, 4, [1,2,3,4,5,6,7,8]이 됩니다. 첫 번째 insert(7)는 7을 노드 3 아래에 삽입하므로 3을 반환하고, 두 번째 insert(8)는 8을 노드 4 아래에 삽입하므로 4를 반환하는 것입니다.

해결 접근 방법

핵심 아이디어는 큐(Queue)를 활용하여 삽입 가능한 위치(자식이 하나만 있는 노드 또는 자식이 없는 노드)를 추적하는 것입니다. 단계별로 살펴보겠습니다.

  1. 큐 q와 멤버 변수 root를 선언합니다.
  2. 생성자에서는 주어진 트리를 순회하며 삽입 후보 노드들을 큐에 채웁니다.
    • root를 멤버 변수에 저장하고, root를 q에 삽입합니다.
    • 무한 루프를 돌며 현재 노드(root)의 왼쪽 자식이 존재하면 q에 추가하고, 없으면 루프를 종료합니다.
    • 오른쪽 자식이 존재하면 q에 추가한 뒤 맨 앞 노드를 제거하고, 다음 후보 노드를 확인합니다. 없으면 루프를 종료합니다.
  3. insert 메서드는 값 v를 인자로 받습니다.
    • parent := q의 맨 앞 요소로 설정하고, 값 v를 가진 새 노드 temp를 만들어 q에 삽입합니다.
    • parent의 왼쪽 자식이 비어 있다면 parent->left = temp로 설정합니다. 그렇지 않다면 q에서 맨 앞 요소를 제거하고, temp를 parent의 오른쪽 자식으로 연결합니다.
    • 부모 노드의 값을 반환합니다.
  4. get_root() 메서드는 저장해 둔 root를 그대로 반환합니다.

이 방식 덕분에 insert 연산은 O(1) 시간에 수행되며, 트리의 완전성이 항상 보장됩니다.

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());
}

입력

트리를 [1,2,3,4,5,6]으로 초기화한 뒤, 7과 8을 삽입하고 루트를 조회

출력

3
4
[1, 2, 3, 4, 5, 6, 7, 8]

마무리

이처럼 큐를 사용하면 완전 이진 트리의 성질을 유지하면서 새 노드를 삽입할 위치를 손쉽게 관리할 수 있습니다. 생성자에서 삽입 후보 노드들을 미리 큐에 정리해 두기 때문에, insert 연산은 상수 시간(O(1))에 처리되고 get_root 역시 즉시 루트를 반환할 수 있습니다.