Last active
September 14, 2015 15:08
-
-
Save klikstermkd/0e9582c91003161dd909 to your computer and use it in GitHub Desktop.
Traverse binary tree using a generator function and an iterator.
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 BinaryTree { | |
constructor(value, left = null, right = null) { | |
this.value = value; | |
this.left = left; | |
this.right = right; | |
} | |
* [Symbol.iterator]() { | |
yield this.value; | |
if (this.left) { | |
yield* this.left; | |
} | |
if (this.right) { | |
yield* this.right; | |
} | |
} | |
} | |
/* Create a tree | |
a | |
/ \ | |
b e | |
/ \ | |
c d | |
*/ | |
let node1 = new BinaryTree('e'); | |
let node2 = new BinaryTree('c'); | |
let node3 = new BinaryTree('d'); | |
let node4 = new BinaryTree('b', node2, node3); | |
let tree = new BinaryTree('a', node4, node1); | |
// Iterate over the tree and print the values | |
for (let value of tree) { | |
console.log(value); | |
} | |
// Output: | |
// a | |
// b | |
// c | |
// d | |
// e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment