Web Toolbar by Wibiya

Pages

Friday, May 20, 2011

Write an algorithm for Breadth-first-search.

A breadth-first-search is one which starts from root node and crawls down exploring neighboring nodes.

Solution #1: We can use a queue to perform BFS. Here is the algorithm,

- Enqueue root node
- Dequeue a node and check it:
    - if it is a match, then return success
    - else enqueue it's children
- Check if queue is empty, if it's empty then return failure, otherwise repeat step 2.

Below is the code,

void bfs(struct node* root)
{
    queue q;

    q.push(root);

    while(!q.empty())
    {
        struct node* temp = q.front();
        q.pop();
        
        printf("%d ", temp->data);

        if(temp->left != NULL)
            q.push(temp->left);

        if(temp->right != NULL)
            q.push(temp->right);
    }

    printf("\n");
}

No comments: