Skip to content

Instantly share code, notes, and snippets.

@jinwolf
Created December 19, 2015 23:34
Show Gist options
  • Select an option

  • Save jinwolf/9c624d37bb6f0d79410c to your computer and use it in GitHub Desktop.

Select an option

Save jinwolf/9c624d37bb6f0d79410c to your computer and use it in GitHub Desktop.
Builds a binary tree from a sorted array and searches a value using the binary tree (JavaScript)
function Node(val) {
this.value = val;
this.left = null;
this.right = null;
}
var numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function buildTree(list, start, end) {
if (start > end) {
return null;
}
var center = Math.floor((start + end) / 2);
var head = new Node(list[center]);
head.left = buildTree(list, start, center - 1);
head.right = buildTree(list, center + 1, end);
return head;
}
var head = buildTree(numList, 0, 9);
//console.log(head);
//console.log(head.left);
//console.log(head.right);
function search(head, num) {
if (head === null) {
return null;
}
if (num === head.value) {
return head;
}
if (num < head.value) {
return search(head.left, num);
} else {
return search(head.right, num);
}
}
console.log(search(head, 3));
console.log(search(head, 1));
console.log(search(head, 5));
console.log(search(head, 11));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment