Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Created March 25, 2018 06:00
Show Gist options
  • Save C-Rodg/5f844b3da7f1a402b72786b966d40849 to your computer and use it in GitHub Desktop.
Save C-Rodg/5f844b3da7f1a402b72786b966d40849 to your computer and use it in GitHub Desktop.
Depth-first searching of a tree using generators.
class Tree {
constructor(value = null, children = []) {
this.value = value;
this.children = children;
}
*printValues() {
yield this.value;
for(let child of this.children) {
yield* child.printValues;
}
}
}
const tree = new Tree(1, [
new Tree(2, [new Tree(4)]),
new Tree(3)
]);
const values = [];
for (let value of tree.printValues()) {
values.push(value);
}
// [1, 2, 4, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment