Skip to content

Instantly share code, notes, and snippets.

@kshirish
Created August 12, 2024 12:44
Show Gist options
  • Save kshirish/f49a9503367e2062b887b6594caf0f38 to your computer and use it in GitHub Desktop.
Save kshirish/f49a9503367e2062b887b6594caf0f38 to your computer and use it in GitHub Desktop.
N-ary Tree
// Creating a sample n-ary tree
// 1
// / | \
// 2 3 4
// / \ |
// 5 6 7
class NaryTreeNode {
constructor(value) {
this.value = value;
this.children = []; // An array to store children nodes
}
}
function dfs(rootNode) {
if (!root) {
return [];
}
const stack = [rootNode];
const result = []; // This will store the values in DFS order
while (stack.length > 0) {
const node = stack.pop();
result.push(node.value);
// Push all children onto the stack in reverse order
// so that the leftmost child is processed first.
for (let i = node.children.length - 1; i >= 0; i--) {
stack.push(node.children[i]);
}
}
return result;
}
const root = new NaryTreeNode(1);
const child1 = new NaryTreeNode(2);
const child2 = new NaryTreeNode(3);
const child3 = new NaryTreeNode(4);
const child4 = new NaryTreeNode(5);
const child5 = new NaryTreeNode(6);
const child6 = new NaryTreeNode(7);
root.children.push(child1, child2, child3);
child1.children.push(child4, child5);
child3.children.push(child6);
// DFS traversal
const dfsResult = dfs(root);
console.log(dfsResult); // Output: [1, 2, 5, 6, 3, 4, 7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment