标签:javascript 对象 哈夫曼树 function js
function Node(data) { this.data = data; this.left = null; this.right = null; } Array.prototype.createHufuTree = function() { var nodes = []; /*初始化结点*/ for (var i = 0; i < this.length; i++) { nodes.push(new Node(this[i])); } while (nodes.length > 1) { nodes.sort(function(a, b) { return a.data - b.data; }); var one = nodes.shift(); var two = nodes.shift(); var sum = one.data + two.data; /*构造结点*/ var root = new Node(sum); root.left = new Node(one); root.right = new Node(two); nodes.unshift(root); } return nodes[0]; } /*测试用例*/ var datasarray = [1, 54, 23, 64, 53, 87, 97]; var res = datasarray.createHufuTree();
标签:javascript 对象 哈夫曼树 function js
原文地址:http://blog.csdn.net/primary_wind/article/details/40261059