问题
In order to do level order(BFS) traversal of a generic tree I wrote the following display function for the code mentioned in the link below. The problem is that each level is printed twice. Can someone tell me why. Original Code without this function can be found in the link below in case someone need the entire implementation else just look at the displayBFS function below and tell me why are values repeating
Level Order traversal of a generic tree(n-ary tree) in java
Thanks!
void displayBFS(NaryTreeNode n)
{
Queue<NaryTreeNode> q = new LinkedList<NaryTreeNode>();
if(n!=null)
{
q.add(n);
System.out.println(n.data);
}
while(n!=null)
{
for(NaryTreeNode x:n.nary_list)
{
q.add(x);
System.out.println(x.data );
}
n = q.poll();
}
}
Current Tree Structure for reference:
root(100)
/ | \
90 50 70
/ \
20 30 200 300
Output:
100
90
50
70
90
50
70
20
30
200
300
20
30
200
300
回答1:
The problem is that you process your root-node twice: you initially add it to your queue (in the line q.add(n)
), then you process it before you first get to n = q.poll()
, and then you get it off the queue and process it again.
Everything else is correct, which is why you only get two copies of each non-root node: the doubling only occurs once, at root.
To fix this, either remove the line q.add(n)
(since you process the root node anyway, even without it), or else change this:
while(n!=null)
{
...
n = q.poll();
}
to this:
while((n = q.poll()) != null)
{
...
}
so that you don't process the root node that initial extra time.
来源:https://stackoverflow.com/questions/12808215/level-order-traversal-of-a-tree