341. Flat nested list iterators

Answer:

  1. Input:NestedList = [(1, 1), 2, [1, 1]]When,nestedList[0]Is also aNestedIntegerType, justnestedList[0].getInteger() === null.
  2. Can benestedListAs a tree, each node can pass throughgetIntegerMethod to get the current valuegetListMethod to obtain the next layer node.
  3. useDFS, first search for the values of all nodes in the tree, the values are stored in the array.
  4. Using a pointerindex, always pointing tonextCorresponding value position. Each callnext, both move the pointer back one bit. ifindexThe pointing type isnumber.hasNextreturntrue.
/ * * *@constructor
 * @param {NestedInteger[]} nestedList* /
var NestedIterator = function (nestedList) {
  this.list = []; // Use arrays to store values for each node
  this.index = 0; // Always point to the next element with a pointer

  // Use DFS to search all results and initialize
  const dfs = (nestedList) = > {
    // Iterate over each element of the array
    for (const nestedInteger of nestedList) {
      // Get the current element value
      const value = nestedInteger.getInteger();

      // If the current value exists, it is stored in the array
      if (typeof value === 'number') {
        this.list.push(value);
      }

      // Continue searching for the next level of the element listdfs(nestedInteger.getList()); }};/ / search nestedList
  dfs(nestedList);
};

/ * * *@this NestedIterator
 * @returns {boolean}* /
NestedIterator.prototype.hasNext = function () {
  // If the value type corresponding to the pointer is number, the next item exists; otherwise, undefined
  return typeof this.list[this.index] === 'number';
};

/ * * *@this NestedIterator
 * @returns {integer}* /
NestedIterator.prototype.next = function () {
  // Return the current value and move the pointer back
  return this.list[this.index++];
};
Copy the code