i trying write recursive generator in order traversal.
class tree { *inordertraversal() { function* helper(node) { if (node.left !== null) { // line executed, helper not being called helper(node.left); } yield node.value; if (node.right !== null) { helper(node.right); } } (let of helper(this.root)) { yield i; } } // other methods omitted }
and calling generator so:
const tree = new tree(); tree.add(2); tree.add(1); tree.add(3); (let of tree.inordertraversal()) { console.log(i); // prints 2 }
why generator yielding 2
? why @ least not yielding 1
before 2
?
how can fix this?
if helps, transpiling code using babel.
babel --optional runtime test.js | node
the problem not recursion. function did call recursively, didn't yield values outside. when call helper(), iterator return value, wanted iterated values of iterator yielded. if want yield recursively, need yield *
. try this:
* inordertraversal() { function* helper(node) { if (node.left !== null) { // line executed, helper not being called yield * helper(node.left); } yield node.value; if (node.right !== null) { yield * helper(node.right); } } (let of helper(this.root)) { yield i; } }
and while you're @ it, can replace for
loop with:
yield * helper(this.root)
Comments
Post a Comment