C_C++

(C언어) 연결 리스트로 이진 트리 구현

고니자니 2023. 11. 1. 17:44
반응형

C 언어를 이용하여 트리(Tree)를 구현하는 방법은 여러 가지가 있습니다.

트리 구조는 많은 종류가 있으며,  여기서는 이진 트리(Binary Tree)를 구현하는 예제입니다.

이진 트리는 각 노드가 최대 두 개의 자식 노드를 가지는 트리입니다.

먼저, 이진 트리의 간단한 구조를 정의해 보겠습니다. 각 노드는 데이터와 두 개의 포인터(왼쪽 자식 노드 및 오른쪽 자식 노드를 가리키는 포인터)로 구성됩니다. 

 

아래는 이진 트리의 구조를 정의한 C 코드입니다.

#include <stdio.h>
#include <stdlib.h>

// 이진 트리 노드 구조체 정의
struct TreeNode {
    int data;
    struct TreeNode* left;
    struct TreeNode* right;
};

// 새로운 노드를 생성하는 함수
struct TreeNode* createNode(int data) {
    struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    if (newNode == NULL) {
        printf("메모리 할당 오류\n");
        exit(1);
    }
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {
    // 트리 노드 생성
    struct TreeNode* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);

    // 이진 트리 출력
    printf("이진 트리:\n");
    printf("    1\n");
    printf("   / \\ \n");
    printf("  2   3\n");
    printf(" / \\ \n");
    printf("4   5\n");

    return 0;
}

(C언어) 이진 트리(binary tree) 구현

 

 

728x90
반응형