The problem is that you process your root node twice: first add it to your turn (on the q.add(n) ), then process it before you go to n = q.poll() , and then get it off the line and process it again.
Everything else is correct, so you only get two copies of each non-root node: doubling happens only once, at the root.
To fix this, delete the q.add(n) (since you are still the root file of the node, even without it), or change this:
while(n!=null) { ... n = q.poll(); }
:
while((n = q.poll()) != null) { ... }
so that you do not process the root node this is extra time.
source share