回溯实现
// 节点对象
function Node(data, left, right, index, numberIndex) {
this.data = data; // 节点值
this.left = left || null; // 当前节点的左子节点
this.right = right || null; // 当前节点的右子节点
this.index = index;
this.leaf = false;
if (!left && !right) {
this.leaf = true;
}
if (data === null) {
this.left = null;
this.right = null;
this.leaf = true;
}
this.numberIndex = numberIndex
}
let data = [0, 1, 2,null,4,5,6,7];
function er(data) {
data[0] = new Node(data[0], data[1], data[2], 0, { leftIndex: 1, rightIndex: 2 });
data.unshift(null);
let index = 0,
tempI = 0;
for (let i = 2; i < data.length; i++) {
index = Math.log2(i);
if (index === Math.floor(index)) {
tempI = 2 * i;
}
data[i] = new Node(data[i], data[tempI++], data[tempI], Math.floor(index), { leftIndex: tempI - 2, rightIndex: tempI - 1 });
tempI++;
}
data.shift()
function Leaf(params) {
if (!params||params.leaf) return params;
if (params.left) { params.left = Leaf(data[params.numberIndex.leftIndex]); }
if (params.right) { params.right = Leaf(data[params.numberIndex.rightIndex]); }
return params;
}
return Leaf(data[0]);
}
console.log(er(data));
堆的元素存储方式,按照完全二叉树的顺序存储方式存储在一个一维数组中
参考地址:https://mp.weixin.qq.com/s/R0G-2BOFqwHAgiqfuIEXwg