Skip to content

Instantly share code, notes, and snippets.

@kshirish
Last active August 13, 2024 02:59
Show Gist options
  • Save kshirish/5562243c940369efca378e070117697e to your computer and use it in GitHub Desktop.
Save kshirish/5562243c940369efca378e070117697e to your computer and use it in GitHub Desktop.
Binary Tree Array
// Binary tree represented as an array
// 1
// / \
// 2 3
// / \ \
// 4 5 6
const tree = [1, 2, 3, 4, 5, null, 6];
function bfs(tree) {
const result = [];
const queue = [];
if (tree.length === 0) return result;
queue.push(0); // Start with the root node index (0)
while (queue.length > 0) {
const nodeIndex = queue.shift(); // Dequeue the front element
if (nodeIndex >= tree.length || tree[nodeIndex] === null) {
continue;
}
result.push(tree[nodeIndex]);
const leftChildIndex = 2 * nodeIndex + 1;
const rightChildIndex = 2 * nodeIndex + 2;
if (leftChildIndex < tree.length) {
queue.push(leftChildIndex);
}
if (rightChildIndex < tree.length) {
queue.push(rightChildIndex);
}
}
return result;
}
// BFS traversal
const bfsResult = bfs(tree);
console.log("BFS:", bfsResult); // Output: [1, 2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment