341. Flat nested list iterators
Answer:
- Input:
NestedList = [(1, 1), 2, [1, 1]]
When,nestedList[0]
Is also aNestedInteger
Type, justnestedList[0].getInteger() === null
. - Can be
nestedList
As a tree, each node can pass throughgetInteger
Method to get the current valuegetList
Method to obtain the next layer node. - use
DFS
, first search for the values of all nodes in the tree, the values are stored in the array. - Using a pointer
index
, always pointing tonext
Corresponding value position. Each callnext
, both move the pointer back one bit. ifindex
The pointing type isnumber
.hasNext
returntrue
.
/ * * *@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