341. Flatten Nested List Iterator

This is an itegrator problem.

You can look nestedList as a tree, just recursively read the nestedList, and put the integration into a list, and then itegrate the list, done!

public class NestedIterator implements Iterator<Integer> {
    List<Integer> list = new ArrayList<>();
    Iterator<Integer> it;
    public NestedIterator(List<NestedInteger> nestedList) {
        helper(nestedList);
        it = list.iterator();
        
    }
    
    private void helper(List<NestedInteger> nestedList){
        for(NestedInteger ni: nestedList){
           if(ni.isInteger()){
              list.add(ni.getInteger());
           }
           else{
              helper(ni.getList());
           }
        }
    }

    @Override
    public Integer next() {
        return it.next();
    }

    @Override
    public boolean hasNext() {
        return it.hasNext();
    }
}

 

上一篇:同事连不上我本地Mysql开账号给别人连接


下一篇:leetcode-617. 合并二叉树