Simple recursive flatten method during Iterator construction


  • 0
    P
    public class NestedIterator implements Iterator<Integer> {
    
        private List<NestedInteger> flattened = new ArrayList<NestedInteger>();
        private int current = 0;
        public NestedIterator(List<NestedInteger> nestedList) {
            flatten(nestedList);
        }
    
        private void flatten(List<NestedInteger> nestedList) {
            
            for (NestedInteger val : nestedList) {
                if (val.isInteger()) {
                    flattened.add(val);
                } else {
                    flatten(val.getList());
                }
            }
        }
        
        @Override
        public Integer next() {
            return flattened.get(current++).getInteger();   
        }
    
        @Override
        public boolean hasNext() {
            return current < flattened.size();
        }
    }

Log in to reply
 

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