Simple Solution with queue


  • 0
    R
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            construct_queue(nestedList);
        }
    
        int next() {
            int ret = q.front();
            q.pop();
            return ret;
        }
    
        bool hasNext() {
            return !q.empty();
        }
    private:    
        void construct_queue(vector<NestedInteger> &nestedList) {
            for (auto& ni : nestedList) {
                if (ni.isInteger()) {
                    q.push(ni.getInteger());
                } else {
                    construct_queue(ni.getList());
                }
            }
        }
        queue<int> q;
    };

  • 0

    So I guess this is a dfs solution. Nice solution!


Log in to reply
 

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