Java DFS Simple solution


  • 0
    C
    public class NestedIterator implements Iterator<Integer> {
        ArrayList<Integer> arr = new ArrayList<>();
        int pos;
        public NestedIterator(List<NestedInteger> l) {
            arr = helper(l);
            pos = 0;
            
        }
        private ArrayList<Integer> helper(List<NestedInteger> l) {
            ArrayList<Integer> list = new ArrayList<>();
            for(NestedInteger temp : l) {
                if(temp.isInteger()) {
                    list.add(temp.getInteger());
                } else {
                    ArrayList<Integer> t = helper(temp.getList());
                    list.addAll(t);
                }
            }
            return list;
        }
        @Override
        public Integer next() {
            int res = arr.get(pos++);
            return res;
        }
    
        @Override
        public boolean hasNext() {
            return pos < arr.size();
        }
    }

Log in to reply
 

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