This is leetcode 341. When I write like this, it is correct:
class NestedIterator {
public:
vector<int> flatted;
int current=0;
NestedIterator(vector<NestedInteger> &nestedList) {
flatten(nestedList);
}
void flatten(vector<NestedInteger> &nestedList)
{
for(NestedInteger i:nestedList)
{
if(i.isInteger())
flatted.push_back(i.getInteger());
else
flatten(i.getList());
}
}
int next() {
current++;
return flatted[current-1];
}
bool hasNext() {
if(current<flatted.size())
return true;
else
return false;
}
};
But, if I write it like this, it is not correct:
class NestedIterator {
public:
vector<int> flatted;
int current=0;
NestedIterator(vector<NestedInteger> &nestedList) {
for(NestedInteger i:nestedList)
{
if(i.isInteger())
flatted.push_back(i.getInteger());
else
NestedIterator(i.getList());
}
}
};
The only difference is that in method 2, I call the constructor recursively. Why is it not correct?