java easy dfs solution, beats 98%

  • 0

    At first, I was planning to use a stack. But then I realize it contains so many corner cases, which make it complex.

    For example, input list like [[[],[],[]]].

    So, I decide to transfer the list into array. Now I don't even have to care about those corner cases.

    public class NestedIterator implements Iterator<Integer> {
        private List<Integer> list;
        private int cur;
        public NestedIterator(List<NestedInteger> nestedList) {
            this.list = new ArrayList<>();
            int cur = 0;
            ini(list, nestedList);
        public Integer next() {
            return list.get(cur++);
        public boolean hasNext() {
            return cur != list.size();
        private void ini(List<Integer> list, List<NestedInteger> nestedList) {
            for(NestedInteger ni : nestedList) {
                if(ni.isInteger()) {
                } else {
                    ini(list, ni.getList());

Log in to reply

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