[c++] 트리(Tree) 데이터 구조

이번에는 C++에서 트리(Tree) 데이터 구조를 어떻게 구현하는 지에 대해 알아보겠습니다. 트리는 계층적인 관계를 표현하는 데 사용되는 자료 구조로, 노드(Node)들이 간선(엣지)로 연결된 구조를 가지고 있습니다. 각 노드는 자식 노드를 가질 수 있으며, 맨 위에 있는 노드를 루트(Root) 노드라고 합니다.

이진 트리(Binary Tree) 예제

다음은 C++로 간단한 이진 트리를 구현한 예제입니다.

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
};

class BinaryTree {
public:
    Node* root;

    BinaryTree() {
        root = nullptr;
    }

    Node* createNode(int data) {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->left = nullptr;
        newNode->right = nullptr;
        return newNode;
    }

    void insert(int data) {
        root = insertRec(root, data);
    }

    Node* insertRec(Node* root, int data) {
        if (root == nullptr) {
            return createNode(data);
        }

        if (data < root->data) {
            root->left = insertRec(root->left, data);
        } else {
            root->right = insertRec(root->right, data);
        }

        return root;
    }
};

int main() {
    BinaryTree tree;
    tree.insert(10);
    tree.insert(5);
    tree.insert(15);
    return 0;
}

위 예제에서는 Node 구조체를 정의하고, BinaryTree 클래스에 이진 트리를 만들기 위한 기본적인 기능들을 추가했습니다. 이 예제는 노드를 삽입하는 간단한 이진 트리를 보여줍니다.

이렇게 C++를 사용하여 트리 구조를 구현할 수 있으며, 실제 프로젝트에서 트리를 활용하여 데이터를 구조화하는 데에 유용하게 활용될 수 있습니다.

참고 자료