level wise linked list of nodes of binary tree

Given a binary tree build a linked list of all its nodes such that the nodes of a level appear before the nodes of the next level?

Comments

  1. llist(struct node *root)
    {
    struct node *r,*p;
    struct node *head=NULL;
    if(root==NULL)
    return;
    else{
    push(queue,root);
    while(queue is not empty)
    {
    r=pop(queue);
    if(r->left!=NULL)
    push(queue,r->left);
    if(r->right!=NULL)
    push(queue,r->right);

    if(head==NULL)
    {
    head=r;
    r->next=NULL;
    p=r;
    }

    else{
    p->next=r;
    r->next=NULL;
    p=r;
    }
    }
    }
    return;
    }

    ReplyDelete
  2. @kamakshi can you explain your approach,because reading code is little bit time taking.:)

    ReplyDelete
  3. I used a queue for storing the nodes of a tree.first the root is pushed in the queue.now till the queue is not empty it pops one node(say x) from the queue and push(x->left and x->right)into the queue only if they are not null.the elements popped out can make a linked list.

    ReplyDelete

Post a Comment

Popular posts from this blog