Easy understanding recursive C++ method


  • 0
    S
    NestedIterator(vector<NestedInteger> &nestedList) {
        getAll(nestedList, res);
        i = 0;
    }
    
    void getAll(vector<NestedInteger> &nestedList, vector<int>& res) {
        int n = nestedList.size();
        
        for (int i=0; i<n; i++) {
            NestedInteger tmp = nestedList[i];
            if (tmp.isInteger()) {
                res.push_back(tmp.getInteger());
            } else {
                getAll(tmp.getList(), res);
            }
        }
    }
    
    int next() {
        int val = res[i];
        i++;
        return val;        
    }
    
    bool hasNext() {
        return i < res.size();
    }
    
    // private variables;
    vector<int> res;
    int i = 0;
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.