Estoy tratando de resolver esta pregunta de leetcode https://leetcode.com/problems/binary-search-tree-iterator/ donde le pide que realice una iteración para atravesar el BST y pensé que los generadores son una buena opción para ello.
Aquí está mi intento
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 } }Pero tengo un error diciendo
TypeError: yield* is not a terable¿Alguien puede ayudarme a entender dónde hice mal y cuáles son las soluciones correctas a este problema mediante el uso de generadores?
Algunos problemas:
yield* this._genGen(node.right) ... cámbielo para get con una t .done tendrá el valor booleano opuesto al que debe devolver hasNext , por lo que debe negarlodone cuando ya haya realizado una llamada .next() en el iterador. Por lo tanto, necesita que el iterador esté siempre un paso adelante y recuerde su valor de retorno en el estado de su instancia.Así que así es como puedes cambiar tu código:
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; } }