Clean recursive Java solution, 5ms


  • 0
    L
    public class NestedIterator implements Iterator<Integer> { 
        private List<Integer> ints = new ArrayList<>();
        private int i = 0;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            addAll(nestedList);
        }
        
        private void addAll(List<NestedInteger> nestedList) {
            for (NestedInteger ni : nestedList) {
                if (ni.isInteger()) {
                    ints.add(ni.getInteger());
                } else {
    		addAll(ni.getList());
               }
            }
        }
    
        @Override
        public Integer next() {
            Integer o = ints.get(i);
            i++;
            return o;
        }
    
        @Override
        public boolean hasNext() {
            return i < ints.size();
        }
    }
    

Log in to reply
 

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