C언어 트리 구현

1 개요[ | ]

C언어 트리 구현
#include <stdio.h>

#define MAX_NODE_NUM 10000
#define MAX_CHILD_NUM 2

typedef struct {
    int parent;
    int child[MAX_CHILD_NUM];
} TreeNode;

TreeNode tree[MAX_NODE_NUM];
int nodeNum;

void init() {
    for (int i = 0; i < MAX_NODE_NUM; i++) {
        tree[i].parent = -1;
        for (int j = 0; j < MAX_CHILD_NUM; j++) {
            tree[i].child[j] = -1;
        }
    }
}

void addChild(int parent, int child) {
    for (int i = 0; i < MAX_CHILD_NUM; i++) {
        if (tree[parent].child[i] == -1) {
            tree[parent].child[i] = child;
            tree[child].parent = parent;
            return;
        }
    }
}

int getRoot() {
    for (int i = 0; i < nodeNum; i++) {
        if (tree[i].parent == -1) {
            return i;
        }
    }
    return -1; // 루트를 찾지 못한 경우
}

void preOrder(int root) {
    if (root == -1) return; // 유효하지 않은 루트인지 점검
    printf("%d ", root);
    for (int i = 0; i < MAX_CHILD_NUM; i++) {
        preOrder(tree[root].child[i]);
    }
}

int main() {
    init();
    nodeNum = 5; // 총 노드 개수 설정
    addChild(0, 1);
    addChild(0, 2);
    addChild(1, 3);
    addChild(1, 4);

    // 루트 노드 찾기
    int root = getRoot();
    printf("%d\n", root); // 0

    // 전위 순회 결과 출력
    preOrder(root); // 0 1 3 4 2 
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}