C++ solution, dfs with a vector


  • 0
    F
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            for(int i = 0; i < nestedList.size(); i++)
                dfs(nestedList[i]);
        }
        void dfs(NestedInteger &nsList) {
            if(nsList.isInteger())
                vec.push_back(nsList.getInteger());
            vector<NestedInteger> tmp = nsList.getList();
            for(int i = 0; i < tmp.size(); i++)
                dfs(tmp[i]);
        }
    
        int next() {
            return vec[top ++];
        }
    
        bool hasNext() {
            return top < vec.size();
        }
    private:
        int top = 0;
        vector<int> vec;
    };

Log in to reply
 

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