Created
May 18, 2024 12:39
-
-
Save carefree-ladka/18ebec0dd4db1e92620130094f87449b to your computer and use it in GitHub Desktop.
Nry Tree Implementation
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
| class Node { | |
| constructor(val) { | |
| this.val = val; | |
| this.children = []; | |
| } | |
| addChild = (child) => this.children.push(child) | |
| } | |
| class NryTree { | |
| constructor(value) { | |
| this.root = new Node(value) | |
| } | |
| dfs = (node=this.root, result=[]) => { | |
| if (!node) return | |
| result.push(node.val); | |
| for (const child of node.children) this.dfs(child, result) | |
| return result | |
| } | |
| bfs = (result = []) => { | |
| const queue = [this.root] | |
| while (queue.length) { | |
| const current = queue.shift() | |
| result.push(current.val); | |
| for (const child of current.children) { | |
| queue.push(child) | |
| } | |
| } | |
| return result | |
| } | |
| } | |
| const nry = new NryTree(1) | |
| const node1 = new Node(2) | |
| const node2 = new Node(3) | |
| const node3 = new Node(4) | |
| nry.root.addChild(node1) | |
| nry.root.addChild(node2) | |
| nry.root.addChild(node3) | |
| const node4 = new Node(5) | |
| const node5 = new Node(6) | |
| node2.addChild(node4) | |
| node3.addChild(node5) | |
| console.log(JSON.stringify(nry, null,4)); | |
| console.log('dfs',nry.dfs()); | |
| console.log('bfs', nry.bfs()); | |
| /* | |
| { | |
| "root": { | |
| "val": 1, | |
| "children": [ | |
| { | |
| "val": 2, | |
| "children": [] | |
| }, | |
| { | |
| "val": 3, | |
| "children": [ | |
| { | |
| "val": 5, | |
| "children": [] | |
| } | |
| ] | |
| }, | |
| { | |
| "val": 4, | |
| "children": [ | |
| { | |
| "val": 6, | |
| "children": [] | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| } | |
| dfs [ 1, 2, 3, 5, 4, 6 ] | |
| bfs [ 1, 2, 3, 4, 5, 6 ] | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment