Super easy and concise java solution using recursion, only 6ms!


  • 0
    L
    public class NestedIterator implements Iterator<Integer> {
        private Iterator<Integer> iterator;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            List<Integer> res = new ArrayList<>();
            helper(res, nestedList);
            iterator = res.iterator();
        }
        
        private void helper(List<Integer> res, List<NestedInteger> nestedList) {
            for (NestedInteger ni : nestedList) {
                if (ni.isInteger()) res.add(ni.getInteger());
                else helper(res, ni.getList());
            }
        }
    
        @Override
        public Integer next() {
            return iterator.next();
        }
    
        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }
    }
    

Log in to reply
 

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