recursive java version, no stack, 6ms


  • 0
    Y
        private List<NestedInteger> list = new ArrayList<>();    
        private int curr = 0;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            for (NestedInteger ni : nestedList) expand(list, ni);
        }
    
    
        private void expand(List<NestedInteger> list, NestedInteger ni) {
            if (list == null)   return;
            
            if (ni.isInteger()) list.add(ni);
            else for (NestedInteger n: ni.getList())  expand(list, n);
        }
    
    
        @Override
        public Integer next() {
            return list.get(curr++).getInteger();        
        }
    
        @Override
        public boolean hasNext() {
            return curr <= list.size() - 1;
        }
    

Log in to reply
 

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