Recursive Generators in JavaScript

前端 未结 2 498
说谎
说谎 2020-12-29 22:14

I am trying to write a recursive generator for an in order traversal.

class Tree {
  *inOrderTraversal() {
    function* helper(node) {
      if (node.left !         


        
2条回答
  •  失恋的感觉
    2020-12-29 22:44

    helper(node.left); does call the function and create the generator, but the generator function body is never executed because the generator is never advanced. To forward all of its values to the current generator, you can use the yield* keyword, which works just like the

    for (let i of helper(this.root))
        yield i;
    

    you've used in your inOrderTraversal method. And indeed, that should've been a yield* just as well - or even better, there is no reason to make inOrderTraversal a generator function when it can just be a normal method that returns a generator:

    class Tree {
      inOrderTraversal() {
        function* helper(node) {
          if (node.left !== null)
            yield* helper(node.left);
          yield node.value;
          if (node.right !== null)
            yield* helper(node.right);
        }
    
        return helper(this.root);
      }
      … // other methods
    }
    

提交回复
热议问题