C++/C++로 구현하는 자료구조

이진트리 구현하기 - vector 사용

coding-potato 2025. 1. 9. 17:50

// binarytree.h
#pragma once
#include <iostream>
#include <vector>
using namespace std;

class BinaryTree {
public:
vector<int> tree;

// 새로운 값을 뒤에 추가함
void insert(int a) {
tree.emplace_back(a);
}

// vec 안의 값을 순서대로 이진트리에 추가함
void insert_arr(vector<int> vec) {
for (const int& num : vec) {
tree.emplace_back(num);
// this -> insert(num);
}
}

// indx번째 값을 구함
int at(int indx) {
if (indx < tree.size()) {
return tree[indx];
}
return -1;
}

// 왼쪽 자식을 구함
int getLeftChild(int indx) {
int left_indx = indx * 2 + 1;
if (left_indx < tree.size()) {
return tree[left_indx];
}
return -1;
}

// 오른쪽 자식을 구함
int getRightChild(int indx) {
int left_indx = indx * 2 + 2;
if (left_indx < tree.size()) {
return tree[left_indx];
}
return -1;
}

// 모든 노드의 값과 그 자식들의 값을 출력함
void printTree() {
for (int i = 0; i < tree.size(); i++) {
cout << "Node " << i << " : " << tree[i] << " LeftChild : " << getLeftChild(i) << " RightChild : " << getRightChild(i) << endl;
}
}
};


// main.cpp
#include "binarytree.h"
#include <algorithm>
#include <iostream>

int main(void)
{
BinaryTree bt;
vector<int> tmp = { 4, 1, 6, 2, 7, 3, 9, 18 ,25 };
bt.insert_arr(tmp);
bt.printTree();

return 0;
}


출력 결과