Reconstruct BST
Reconstruct BST
Last updated
Last updated
// This is an input class. Do not edit.
class BST {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
// O(n^2) time | O(n) space
function reconstructBst(preOrderTraversalValues) {
if(preOrderTraversalValues.length === 0) return null;
const currentValue = preOrderTraversalValues[0];
let rightSubtreeRootIndex = preOrderTraversalValues.length;
for (let i = 1; i < preOrderTraversalValues.length; i++) {
const value = preOrderTraversalValues[i];
if (value >= currentValue) {
rightSubtreeRootIndex = i;
break;
}
}
const leftSubtree = reconstructBst(preOrderTraversalValues.slice(1, rightSubtreeRootIndex));
const rightSubtree = reconstructBst(preOrderTraversalValues.slice(rightSubtreeRootIndex));
return new BST(currentValue, leftSubtree, rightSubtree);
}
// Do not edit the lines below.
exports.BST = BST;
exports.reconstructBst = reconstructBst;
// This is an input class. Do not edit.
class BST {
constructor(value, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
class TreeInfo {
constructor(rootIndex) {
this.rootIndex = rootIndex;
}
}
// O(n) time | O(n) space
function reconstructBst(preOrderTraversalValues) {
const treeInfo = new TreeInfo(0);
return reconstructBstHelper(-Infinity, Infinity, preOrderTraversalValues, treeInfo);
}
function reconstructBstHelper(lowerBound, upperBound, preOrderTraversalValues, currentSubtreeInfo) {
if (currentSubtreeInfo.rootIndex === preOrderTraversalValues.length) return null;
const rootValue = preOrderTraversalValues[currentSubtreeInfo.rootIndex];
if (rootValue < lowerBound || rootValue >= upperBound) return null;
currentSubtreeInfo.rootIndex++;
const leftSubtree = reconstructBstHelper(lowerBound, rootValue, preOrderTraversalValues, currentSubtreeInfo);
const rightSubtree = reconstructBstHelper(rootValue, upperBound, preOrderTraversalValues, currentSubtreeInfo);
return new BST(rootValue, leftSubtree, rightSubtree)
}
// Do not edit the lines below.
exports.BST = BST;
exports.reconstructBst = reconstructBst;