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();
时间: 2024-10-28 15:14:54