Short Java recursive solution


  • 0
    G
    public class NestedIterator implements Iterator<Integer> {
        
        private List<Integer> flattened = null;
        private Iterator<Integer> flattenedItr = null;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            if (nestedList != null) {
                flattened = new ArrayList<>();
                flatten(nestedList, flattened);
                flattenedItr = flattened.iterator();
            }
        }
        
        @Override
        public Integer next() {
            return flattenedItr == null ? null : flattenedItr.next();
        }
    
        @Override
        public boolean hasNext() {
            return flattenedItr == null ? false : flattenedItr.hasNext();
        }
        
        private void flatten(List<NestedInteger> nestedList, List<Integer> flattened) {
            for (NestedInteger nInt : nestedList) {
                List<NestedInteger> nList = nInt.getList();
                if (nList == null) {
                    // Is integer
                    flattened.add(nInt.getInteger());
                } else {
                    flatten(nList, flattened);
                }
            }
        }
    }
    

Log in to reply
 

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