Skip to content

Instantly share code, notes, and snippets.

@jalakpatoliya
Created March 16, 2021 12:05
Show Gist options
  • Save jalakpatoliya/501692f568f1992f4b3cad8774409a81 to your computer and use it in GitHub Desktop.
Save jalakpatoliya/501692f568f1992f4b3cad8774409a81 to your computer and use it in GitHub Desktop.
const isValidBST = (root = [5, 1, 4, null, null, 3, 6]) => {
for (let currentRootIndex = 0; currentRootIndex < root.length; currentRootIndex++) {
let isValid = true;
const rootValue = root[currentRootIndex];
const leftChildIndex = currentRootIndex * 2 + 1;
const rightChildIndex = currentRootIndex * 2 + 2;
const leftChildValue = root[leftChildIndex]
const rightChildValue = root[rightChildIndex]
// console.log({
// currentRootIndex,
// leftChildIndex,
// rightChildIndex,
// rootValue,
// leftChildValue,
// rightChildValue
// });
if (leftChildValue) {
if (leftChildValue > rootValue) return false;
}
if (rightChildValue) {
if (rightChildValue < rootValue) return false;
}
}
return true;
}
console.log({ isValidBST: isValidBST() });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment