Skip to content

Instantly share code, notes, and snippets.

@super-fishz
Created February 29, 2020 16:30
Show Gist options
  • Save super-fishz/3bc213c4c0d2099cb859dcdde58166cc to your computer and use it in GitHub Desktop.
Save super-fishz/3bc213c4c0d2099cb859dcdde58166cc to your computer and use it in GitHub Desktop.
const sam1 = [3, 2, 1, 5, 4, 6]
const sam2 = [1, 2, 3]
const sam3 = [1, 3, 4, 2]
const sam4 = [3, 4, 5, 1, 2]
function Node(data) {
this.data = data;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.insert = function(root, data, p_node = null) {
if (root === null) {
this.data = new Node(data);
return this.data;
}
if (p_node)
console.log(p_node.data, root.data, data)
if (data <= root.data) {
if (root.left) {
this.insert(root.left, data, root);
} else if (root.right == null) {
root.left = new Node(data);
}
} else {
if (root.right) {
this.insert(root.right, data, root);
} else {
root.right = new Node(data);
}
}
return this.root;
};
}
function getSize(root) {
if (root == null)
return 0
return getSize(root.left) + getSize(root.right) + 1
}
function solution(arr) {
// generate node
const root = new BinarySearchTree().insert(null, arr.slice(0, 1)[0]);
arr.slice(1, arr.length).forEach(it => new BinarySearchTree().insert(root, it));
return getSize(root) == arr.length
}
console.log(`expect\t: true \nactual\t: ` + solution(sam1))
console.log(`expect\t: true \nactual\t: ` + solution(sam2))
console.log(`expect\t: false \nactual\t: ` + solution(sam3))
console.log(`expect\t: false \nactual\t: ` + solution(sam4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment