Responsive Ads Here

Friday, 5 May 2017

Level order traversal of a tree (only function in c++)

code:--


void LevelOrder(node * root)
{
std::queue<node *> q;// we use queue stl container and have pointer type of node
if(root)//for not null
    {
    q.push(root);
    while(!q.empty())
        {
        cout<<q.front()->data<<" ";
        if((q.front())->left)    //push left child into queue if it's not null
            q.push((q.front())->left);
        if((q.front())->right)    //push right child into queue if it's not null
            q.push((q.front())->right);
        q.pop();
        }
    }
}

No comments:

Post a Comment