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