Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created August 13, 2024 03:06
Show Gist options
  • Save kshirish/6c206bba29881c1129c91600bb7bcc7f to your computer and use it in GitHub Desktop.
Save kshirish/6c206bba29881c1129c91600bb7bcc7f to your computer and use it in GitHub Desktop.
Binary Tree Array - children
// Binary tree represented as an array
// 1
// / \
// 2 3
// / \ \
// 4 5 6
const tree = [1, 2, 3, 4, 5, null, 6];
function getChildrenByNode(tree, node) {
for (let i = 0; i < tree.length; i++) {
if(tree[i] === node) {
let results = [];
if(2 * i < tree.length) {
results.push(tree[2*i + 1]);
}
if((2 * i + 1) < tree.length) {
results.push(tree[2*i + 2]);
}
return results;
}
}
}
console.log(getChildrenByNode(tree, 2));
console.log(getChildrenByNode(tree, 3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment