Simple Recursive Explanation With Code C++

We are going to store all elments after flattening in an array and use an iterator to traverse and check its emptiness.
So, for each NestedInteger element present in the list, there are two choices, either its a single element (integer) or a list.

  1. If it's a single element, we push into our result array and proceed for next element in the list.
  2. But, if it's a list, we would call the recursive function for this list and it will resolve the current and all lists present in this list, finally after coming back, it will go for next.

C++ implementation is given here for your reference:-

class NestedIterator {
    void recur(vector<NestedInteger> &nestedList, vector<int> &integers) {
        for(int i=0;i<nestedList.size();i++) {
            if(nestedList[i].isInteger()) integers.push_back(nestedList[i].getInteger());  // a single element
            else recur(nestedList[i].getList(),integers);  // a list
        }
    }
    vector<int> integers;  // for storing each integer after flattening
    vector<int>::iterator itr;  // iterator for traversing
public:
    NestedIterator(vector<NestedInteger> &nestedList) {
        recur(nestedList,integers);  // resolving the input list
        itr=integers.begin();
    }
    
    int next() {
        return *(itr++);
    }
    
    bool hasNext() {
        if(itr==integers.end()) return 0;
        return 1;
    }
};```
Comments (0)