recursive java version, no stack, 6ms

  • 0
        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);
        public Integer next() {
            return list.get(curr++).getInteger();        
        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.