Java DFS


  • 1
    O
    public class NestedIterator implements Iterator<Integer> {
        
        LinkedList<Integer> list;
        public NestedIterator(List<NestedInteger> nestedList) {
            list = new LinkedList<Integer>();
            dfs(nestedList);
        }
        
        private void dfs(List<NestedInteger> nestedList){
            for(NestedInteger i : nestedList){
                if(i.isInteger()){
                    list.add(i.getInteger());
                }else{
                    dfs(i.getList());
                }
            }
            return;
        }
    
        @Override
        public Integer next() {
            return list.removeFirst();
        }
    
        @Override
        public boolean hasNext() {
            return !list.isEmpty();
        }
    }
    

Log in to reply
 

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