class SegmentTree { constructor(arr, merge) { this.data = arr.slice(); this.tree = []; this.merge = merge; this._buildSegmentTree(0, 0, this.data.length - 1); } _buildSegmentTree(treeIndex, l, r) { if (l === r) { this.tree[treeIndex] = this.data[l]; return; } let leftTreeIndex = this.leftChild(treeIndex); let rightTreeIndex = this.rightCild(treeIndex); let mid = (l + (l + r) / 2) | 0; this._buildSegmentTree(leftTreeIndex, l, mid); this._buildSegmentTree(rightTreeIndex, mid + 1, r); // 根据子节点创建父节点 this.tree[treeIndex] = this.merge(this.tree[leftTreeIndex], this.tree[rightTreeIndex]); } leftChild(index) { return index * 2 + 1; } rightCild(index) { return index * 2 + 2; } }let arr = [1, 2, 3];let segTree = new SegmentTree(arr, (a, b) => a + b);console.log(segTree.tree);
largeQ
人到中年有点甜
相关分类