Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Last active April 23, 2020 22:34
Show Gist options
  • Save gkucmierz/3a990d4652503c013e9429caff963d05 to your computer and use it in GitHub Desktop.
Save gkucmierz/3a990d4652503c013e9429caff963d05 to your computer and use it in GitHub Desktop.
convert array to BST - binary search tree
const arrayToBst = arr => {
const [LEFT, VALUE, RIGHT] = [0, 1, 2];
const node = [null, null, null]
const bst = node.slice();
arr.map(el => {
let tmp = bst;
while (tmp[VALUE] !== null) {
const branch = el < tmp[VALUE] ? LEFT : RIGHT;
if (tmp[branch] === null) {
tmp[branch] = node.slice();
}
tmp = tmp[branch];
}
tmp[VALUE] = el;
});
return bst;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment