Created
May 13, 2015 04:07
-
-
Save FlandreDaisuki/4af2ac4e17412583ceed to your computer and use it in GitHub Desktop.
Simple implement of Huffman tree encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var question = [9, 4, 7, 20, 8, 11, 3]; | |
var q = question.map(function(e){ | |
return {left:null, right:null, num:e} | |
}) | |
// {}是一個有左右樹的結構,若節點左右皆為null為葉節點 | |
for(var i = 0; i < question.length-1; i++) { | |
//迴圈 n-1 次 | |
q.sort(function(a, b){return a.num-b.num}); | |
//從小到大排序 | |
var x = {left:q[0], right:q[1], num:q[0].num+q[1].num}; | |
//最小的作為左樹,次小的作為右樹,num為左右樹總和的總和 | |
q = q.slice(2); | |
//pop前兩個小的 | |
q.push(x); | |
//push剛剛做的x | |
} | |
// q 現在為只有一個元素的陣列 | |
(function traverse (q, str) { | |
if (q.left !== null) { | |
traverse(q.left , str+'0'); | |
} | |
if(q.right !== null) { | |
traverse(q.right , str+'1'); | |
} | |
if(q.left === null && q.right === null) { | |
//葉節點 | |
console.log('node:'+q.num+', encode:'+str); | |
} | |
})(q[0], '') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment