Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
JavaScript: usando Generator para hacer un árbol de búsqueda binario en iterador de orden

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Algunos problemas:

  • Hay un error tipográfico en 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 negarlo
  • Solo sabrá qué se done 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; } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!