6ms Java Solution using recursion instead of stack


  • 1
    K

    I use a private recursive function flatten to flatten nestedList when NestedIterator is initialized.

    public class NestedIterator implements Iterator<Integer> {
        private List<Integer> flatList;
        private int index;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            flatList = new ArrayList<>();
            flatten(nestedList);
        }
        
        private void flatten(List<NestedInteger> nestedList) {
            for (NestedInteger ni : nestedList) {
                if (ni.isInteger()) {
                    flatList.add(ni.getInteger());
                } else {
                    flatten(ni.getList());
                }
            }
        }
    
        @Override
        public Integer next() {
            return hasNext() ? flatList.get(index++) : null;
        }
    
        @Override
        public boolean hasNext() {
            return index < flatList.size();
        }
    }
    

Log in to reply
 

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