Skip to content

Instantly share code, notes, and snippets.

@heatherbooker
Created December 9, 2016 23:17
Show Gist options
  • Save heatherbooker/e9b755fa11a0c1f7a31d151a3f51fabf to your computer and use it in GitHub Desktop.
Save heatherbooker/e9b755fa11a0c1f7a31d151a3f51fabf to your computer and use it in GitHub Desktop.
const nodes = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
const tree = { node: nodes[0], children: [{}, {}] };
addNodes(tree.children[0], nodes[1], 1);
addNodes(tree.children[1], nodes[2], 2);
function addNodes(theRoot, node, index) {
if (!nodes[index]) {
return;
}
theRoot.node = node;
const firstChildIndex = index * 2 + 1;
const secondChildIndex = index * 2 + 2;
if (firstChildIndex > nodes.length - 1) {
return;
}
else if (secondChildIndex > nodes.length - 1) {
theRoot.children = [{}];
} else {
theRoot.children = [{}, {}];
}
addNodes(theRoot.children[0], nodes[firstChildIndex], firstChildIndex);
addNodes(theRoot.children[1], nodes[secondChildIndex], secondChildIndex);
}
console.log(JSON.stringify(tree, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment