Created
August 13, 2024 03:06
-
-
Save kshirish/6c206bba29881c1129c91600bb7bcc7f to your computer and use it in GitHub Desktop.
Binary Tree Array - children
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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