【问题标题】:JavaScript: using Generator to make Binary Search Tree In order IteratorJavaScript:使用生成器制作二叉搜索树的顺序迭代器
【发布时间】:2021-10-04 06:02:34
【问题描述】:

我正在尝试解决这个 leetcode 问题 https://leetcode.com/problems/binary-search-tree-iterator/,它要求您进行迭代以遍历 BST,我认为生成器非常适合它。

这是我的尝试


class BSTIterator {
    constructor(root) {
        this.root = root
        this._gen = this._getGen(root)
    }
    
    *_getGen(node) {
        if(node) {
            yield* this._getGen(node.left)
            yield node.val
            yield* this._genGen(node.right)    
        } 
    }
    
    
    next() {
        return this._gen.next().value
    }
    
    hasNext() {
        return this._gen.next().done
    }
}

但我收到一个错误提示

TypeError: yield* is not a terable

有人可以帮助我了解我做错了什么以及使用生成器解决此问题的正确方法是什么?

【问题讨论】:

  • 切向相关 - 您的 hasNext 无法正常工作,因为它正在消耗下一个值。因此,hasNext() 可能会报告 true,但它消耗了最后一个值,因此在这种情况下,next 不会返回任何内容。

标签: javascript ecmascript-6 binary-search-tree es6-generator


【解决方案1】:

几个问题:

  • yield* this._genGen(node.right) 中有错字...将其更改为 gett
  • done 将具有与 hasNext 应该返回的相反的布尔值,因此您需要否定它
  • 只有在迭代器上调用了.next() 后,您才会知道done 是什么。因此,您需要迭代器始终领先一步,并在您的实例状态下记住它的返回值。

因此,您可以通过以下方式更改代码:

class BSTIterator {
    constructor(root) {
        this.root = root;
        this._gen = this._getGen(root);
        // Already call `next()`, and retain the returned value
        this.state = this._gen.next();
    }
    
    *_getGen(node) {
        if (node) {
            yield* this._getGen(node.left);
            yield node.val;
            yield* this._getGen(node.right); // fix typo
        } 
    }
    
    next() {
        let {value} = this.state; // This has the value to return
        this.state = this._gen.next(); // Already fetch next
        return value;
    }
    
    hasNext() {
        // Get `done` from the value already retrieved, and invert:
        return !this.state.done;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多