Skip to content

Instantly share code, notes, and snippets.

@thurt
Last active April 10, 2016 17:29
Show Gist options
  • Save thurt/cbc278f73dae72a28dc41ab6aef67239 to your computer and use it in GitHub Desktop.
Save thurt/cbc278f73dae72a28dc41ab6aef67239 to your computer and use it in GitHub Desktop.
(() => {
class BinaryTree {
constructor(value, left = null, right = null) {
this.value = value
this.left = left
this.right = right
}
[Symbol.iterator]() {
var tree = [this.value, this.left, this.right]
return {
next() {
let node = tree.shift()
if (node instanceof BinaryTree) {
tree.splice(0, 0, node.value, node.left, node.right)
return this.next()
}
else if (node === null) {
return this.next()
}
else if (node !== undefined) {
return { value: node }
}
return { done: true }
}
}
}
}
let tree = new BinaryTree('a',
new BinaryTree('b',
new BinaryTree('c'),
new BinaryTree('d')
),
new BinaryTree('e')
);
for (let x of tree) {
console.log(x);
}
// Output:
// a
// b
// c
// d
// e
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment