Skip to content

Instantly share code, notes, and snippets.

@w8r
Created August 21, 2018 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w8r/f71a5ba5b9b7ff4c46505d53a8124a27 to your computer and use it in GitHub Desktop.
Save w8r/f71a5ba5b9b7ff4c46505d53a8124a27 to your computer and use it in GitHub Desktop.
Non-recursive BST build from sorted array
export default function sortedArrayToBST(data) {
let root = {};
const Q = [root];
const stack = [0, data.length - 1];
while (Q.length !== 0) {
const right = stack.pop();
const left = stack.pop();
const cur = Q.pop();
const mid = left + ((right - left) >> 1);
if (left - right === 0) {
cur.data = data[mid];
} else {
if (left < mid) {
cur.left = {};
Q.push(cur.left);
stack.push(left, mid);
}
if (right > mid) {
cur.right = {};
Q.push(cur.right);
stack.push(mid + 1, right);
}
}
}
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment