Skip to content

Instantly share code, notes, and snippets.

@AbeEstrada
Created September 2, 2025 00:19
Show Gist options
  • Select an option

  • Save AbeEstrada/98f86e150f4342a44ca9f678b5620741 to your computer and use it in GitHub Desktop.

Select an option

Save AbeEstrada/98f86e150f4342a44ca9f678b5620741 to your computer and use it in GitHub Desktop.
Exercise: Is This a Binary Search Tree?
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function insert(root, data) {
if (root === null) {
return new Node(data);
}
if (data < root.data) {
root.left = insert(root.left, data);
} else if (data > root.data) {
root.right = insert(root.right, data);
}
return root;
}
function create(values) {
let root = null;
for (let value of values) {
root = insert(root, value);
}
return root;
}
function checkBST(root, min = -Infinity, max = Infinity) {
if (root === null) {
return true;
}
if (root.data <= min || root.data >= max) {
return false;
}
return checkBST(root.left, min, root.data) && checkBST(root.right, root.data, max);
}
function processData(input) {
const lines = input.trim().split("\n");
const values = lines[1].split(" ").map(Number);
// Duplicates?
if (new Set(values).size !== values.length) {
console.log("No");
return;
}
const root = create(values);
console.log(checkBST(root) ? "Yes" : "No");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment