// 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;
}
출력 결과
'C++ > C++로 구현하는 자료구조' 카테고리의 다른 글
c++로 양뱡향 연결 리스트 구현하기 (0) | 2025.02.13 |
---|---|
자료구조 구현하기(C++) - 해시 테이블 (0) | 2025.01.08 |
자료구조 구현하기(C++) - 비선형 자료구조 (0) | 2025.01.07 |
자료구조 구현하기(C++) - 선형 자료구조 (0) | 2025.01.07 |