# 67. 生成哈夫曼树

67 67-1

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', function(line) {
    rl.on('line', function(line) {
        const values = line.split(' ').map(Number);
        const root = buildHuffmanTree(values);
        const res = [...traverse(root, [])].join(' ');
        console.log(res);
    });
});

class Node {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

class MinQueue {
    constructor() {
        this.elements = [];
    }

    enqueue(element) {
        this.elements.push(element);
        this.elements.sort((a, b) => a.value - b.value);
    }

    dequeue() {
        return this.elements.shift();
    }

    isEmpty() {
        return this.elements.length === 0;
    }
}

function buildHuffmanTree(values) {
    const pq = new MinQueue();
    values.forEach(v => pq.enqueue(new Node(value)));

    while(pq.elements.length > 1) {
        const left = pq.dequeue();
        const right = pq.dequeue();
        const parent = new Node(left.value + right.value);
        parent.left = left;
        parent.right = right;
        pq.enqueue(parent);
    }

    return pq.dequeue();
}

function traverse(root, arr) {
    if (root) {
        traverse(root.left);
        arr.push(root.value);
        traverse(root.right);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66