Java In Order Traversal Solution


  • 0
    I
        List<Integer> list;
        int ptr;
        public NestedIterator(List<NestedInteger> nestedList) {
            this.list = new ArrayList<>();
            for (NestedInteger n : nestedList) {
                traverse(n, this.list);
            }
            this.ptr = 0;
        }
        
        public void traverse (NestedInteger n, List<Integer> res) {
            if (n.isInteger()) {
                res.add(n.getInteger());
            }
            else {
                List<NestedInteger> nl = n.getList();
                for (NestedInteger curr : nl) {
                    traverse(curr, res);
                }
            }
        }
    
        @Override
        public Integer next() {
            return (list.get(ptr++));
        }
    
        @Override
        public boolean hasNext() {
            return ptr < list.size();
        }
    }

Log in to reply
 

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