Created
August 13, 2024 02:58
-
-
Save kshirish/5a8da134f02acbc03e7284ad94a22d31 to your computer and use it in GitHub Desktop.
Binary Tree Array
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 dfs(tree) { | |
const result = []; | |
const stack = []; | |
if (tree.length === 0) return result; | |
stack.push(0); // Start with the root node index (0) | |
while (stack.length > 0) { | |
const nodeIndex = stack.pop(); // Pop the top element | |
if (nodeIndex >= tree.length || tree[nodeIndex] === null) { | |
continue; | |
} | |
result.push(tree[nodeIndex]); | |
const rightChildIndex = 2 * nodeIndex + 2; | |
const leftChildIndex = 2 * nodeIndex + 1; | |
// Push right child first so that left child is processed first | |
if (rightChildIndex < tree.length) { | |
stack.push(rightChildIndex); | |
} | |
if (leftChildIndex < tree.length) { | |
stack.push(leftChildIndex); | |
} | |
} | |
return result; | |
} | |
// DFS traversal | |
const dfsResult = dfs(tree); | |
console.log("DFS:", dfsResult); // Output: [1, 2, 4, 5, 3, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment