use recursion to really flat the nestedlist, 8ms


  • 0
    M

    Just share my answer to increase the diversity as many are using stack and queue in existing solutions.

    public class NestedIterator implements Iterator<Integer> {
        List<Integer> res = new ArrayList<Integer>();
        int mark = 0;
        public NestedIterator(List<NestedInteger> nestedList) {
            helper(nestedList, res);
            // int end = res.size();
        }
        
        public void helper(List<NestedInteger> nestedList, List<Integer> res) {
            int end = 0;
            for (int idx = 0; idx < nestedList.size(); idx++) {
                NestedInteger curr = nestedList.get(idx);
                if (curr.isInteger() == true) {
                    res.add(curr.getInteger());
                } else {
                    helper(curr.getList(), res);
                }
            }
            return;
        }
        
        @Override
        public Integer next() {
            return res.get(mark-1);
        }
    
        @Override
        public boolean hasNext() {
             if (mark < res.size()) {
                 mark++;
                 return true;
             }
             return false;
        }
    }
    

Log in to reply
 

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