#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
    int weight;
    struct Node *lChild;
    struct Node *rChild;
} Node;

// 比较函数，用于优先队列
int compare(const void *a, const void *b)
{
    return (*(Node **)a)->weight - (*(Node **)b)->weight;
}

// 创建新的节点
Node *createNode(int weight)
{
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->weight = weight;
    newNode->lChild = NULL;
    newNode->rChild = NULL;
    return newNode;
}
// 构建哈夫曼树
Node *createHuffman(int *weights, int size)
{
    Node **nodeArray = (Node **)malloc(size * sizeof(Node *));
    // 初始化节点数组
    for (int i = 0; i < size; i++)
    {
        nodeArray[i] = createNode(weights[i]);
        printf("%d,", nodeArray[i]->weight);
    }
    qsort(nodeArray, size, sizeof(Node *), compare);
    for (int i = 0; i < size; i++)
    {
        printf("%d-", nodeArray[i]->weight);
    }
    // 使用qsort实现优先队列
    for (int i = size; i > 1; i--)
    {
        qsort(nodeArray, i, sizeof(Node *), compare);
        // 找到最右边两个节点
        Node *left = nodeArray[i - 1];
        Node *right = nodeArray[i - 2];
        // 创建新父节点
        Node *parent = createNode(left->weight + right->weight);
        parent->lChild = left;
        parent->rChild = right;
        // 将新节点放入数组中
        nodeArray[i - 2] = parent;
    }

    Node *root = nodeArray[0];
    free(nodeArray);
    return root;
}
// 前序遍历输出
void output(Node *head)
{
    if (head == NULL)
    {
        return;
    }
    printf("%d\n", head->weight);
    output(head->lChild);
    output(head->rChild);
}
// 释放树的内存
void freeTree(Node *root)
{
    if (root == NULL)
    {
        return;
    }
    freeTree(root->lChild);
    freeTree(root->rChild);
    free(root);
}
int main()
{
    int weights[] = {2, 18,  9, 3, 7,25};
    int size = sizeof(weights) / sizeof(weights[0]);
    Node *huffmanTree = createHuffman(weights, size);
    printf("前序遍历halftree:\n");
    output(huffmanTree);
    // 释放树的内存
    freeTree(huffmanTree);
    return 0;
}
