Created
August 12, 2024 12:42
-
-
Save kshirish/d652bfe157fc288d18466256c7a92277 to your computer and use it in GitHub Desktop.
N-ary Tree
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
// 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 bfs(rootNode) { | |
if (!rootNode) { | |
return []; | |
} | |
const queue = [rootNode]; | |
const result = []; // This will store the values in BFS order | |
while (queue.length > 0) { | |
const node = queue.shift(); | |
result.push(node.value); | |
for (let child of node.children) { | |
queue.push(child); | |
} | |
} | |
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); | |
// BFS traversal | |
const bfsResult = bfs(root); | |
console.log(bfsResult); // Output: [1, 2, 3, 4, 5, 6, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment