[c++] 이진 검색 트리(Binary Search Tree)

이진 검색 트리(Binary Search Tree, BST)는 각 노드가 최대 두 개의 자식 노드를 가지며, 특정 순서로 정렬되어 있는 이진 트리입니다. BST는 다음과 같은 특징을 가지고 있습니다.

특징

예시 코드

#include <iostream>
using namespace std;

struct Node {
    int key;
    Node* left;
    Node* right;

    Node(int k) {
        key = k;
        left = right = nullptr;
    }
};

Node* insert(Node* root, int key) {
    if (root == nullptr) {
        return new Node(key);
    }
    
    if (key < root->key) {
        root->left = insert(root->left, key);
    } else if (key > root->key) {
        root->right = insert(root->right, key);
    }
    
    return root;
}

Node* search(Node* root, int key) {
    if (root == nullptr || root->key == key) {
        return root;
    }
    
    if (key < root->key) {
        return search(root->left, key);
    } else {
        return search(root->right, key);
    }
}

void inorder(Node* root) {
    if (root != nullptr) {
        inorder(root->left);
        cout << root->key << " ";
        inorder(root->right);
    }
}

위의 예시 코드는 C++로 이진 검색 트리의 생성, 삽입, 탐색, 및 중위 순회(inorder traversal)를 구현한 것입니다.

BST는 효율적인 데이터 탐색 및 정렬에 사용되므로, 많은 종류의 알고리즘과 데이터 구조에서 사용되고 있습니다.

참고 자료