I am trying to write a recursive generator for an in order traversal.
class Tree {
*inOrderTraversal() {
function* helper(node) {
if (node.left !== null) {
// this line is executed, but helper is not being called
helper(node.left);
}
yield node.value;
if (node.right !== null) {
helper(node.right);
}
}
for (let i of helper(this.root)) {
yield i;
}
}
// other methods omitted
}
And I am calling the generator like so:
const tree = new Tree();
tree.add(2);
tree.add(1);
tree.add(3);
for (let i of tree.inOrderTraversal()) {
console.log(i); // only prints 2
}
Why is the generator only yielding 2
? Why is it at least not yielding 1
before 2
?
How can I fix this?
If it helps, I am transpiling the code using babel.
babel --optional runtime test.js | node
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…