Skip to content

Instantly share code, notes, and snippets.

@klikstermkd
Last active September 14, 2015 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klikstermkd/0e9582c91003161dd909 to your computer and use it in GitHub Desktop.
Save klikstermkd/0e9582c91003161dd909 to your computer and use it in GitHub Desktop.
Traverse binary tree using a generator function and an iterator.
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