Last active
January 19, 2017 02:33
-
-
Save albertywu/afeabbe0782a8d95338a980dd1885028 to your computer and use it in GitHub Desktop.
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 Tree { | |
| constructor(value, children = []) { | |
| this.value = value | |
| this.children = children | |
| } | |
| isLeaf() { | |
| return this.children.length === 0 | |
| } | |
| traverseDepthFirst(fn) { | |
| fn(this) | |
| if (!this.isLeaf()) { | |
| this.children.forEach(n => n.traverseDepthFirst(fn)) | |
| } | |
| } | |
| traverseBreadthFirst(fn) { | |
| const queue = [] | |
| const visited = new Set() | |
| fn(this) | |
| function enqueueChildren(queue, node) { | |
| node.children.forEach(c => queue.push(c) ) | |
| node.children.forEach(c => enqueueChildren(queue, c)) | |
| } | |
| // add all children nodes to queue | |
| enqueueChildren(queue, this) | |
| while (queue.length) { | |
| fn(queue.shift()) | |
| } | |
| } | |
| traverseZigZag(fn) { | |
| function enqueueChildren(nodesByLevel, node, level) { | |
| nodesByLevel[level] = nodesByLevel[level] || [] | |
| node.children.forEach(c => nodesByLevel[level].push(c)) | |
| node.children.forEach(c => enqueueChildren(nodesByLevel, c, level + 1)) | |
| } | |
| const nodesByLevel = {} | |
| const level = 1 | |
| enqueueChildren(nodesByLevel, this, level) | |
| fn(this) | |
| Object.keys(nodesByLevel) | |
| .map(key => [nodesByLevel[key], key]) | |
| .map(([nodes, level]) => level % 2 !== 0 ? nodes : nodes.reverse()) | |
| .reduce((acc, curr) => acc.concat(curr), []) | |
| .forEach(fn) | |
| } | |
| } | |
| const t = new Tree(42, [ | |
| new Tree(12, [ | |
| new Tree(5, []), | |
| new Tree(14, []) | |
| ]), | |
| new Tree(32, [ | |
| new Tree(30, []), | |
| new Tree(36, []) | |
| ]) | |
| ]) | |
| console.log("TRAVERSE [DEPTH-FIRST]:") | |
| t.traverseDepthFirst(n => console.log(n.value)) | |
| console.log("TRAVERSE [BREADTH FIRST]:") | |
| t.traverseBreadthFirst(n => console.log(n.value)) | |
| console.log("TRAVERSE [ZIG-ZAG]:") | |
| t.traverseZigZag(n => console.log(n.value)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment