Level Order Traversal of a tree

梦想与她 提交于 2019-12-25 06:58:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!