Pages

Monday 27 August 2012

convert Bst to sorted circular linked list

Write an efficient function to convert binary search tree into sorted circular doubly linked list. Your function should return the address of first node of resultant list. What are the time and space complexities of your solution?

note:
im building tree here statically

code:
#include<stdio.h>
#include<malloc.h>
struct node
{
    struct node *prev;
    int data;
   struct node *next;
};
struct tree
{
    struct tree *left;
    int data;
    struct tree *right;
};
void append(struct tree**,int);
void treelink(struct tree*,struct node*);
void insertlink(struct node*,int);
void display(struct node*);


void main()
{
    struct tree *head;
    struct node *headlink;
    headlink=(struct node*) malloc(sizeof(struct node));
    headlink->prev=headlink;
    headlink->next=headlink;
    head=NULL;
    append(&head,18);
   append(&head,23);
   append(&head,12);
   append(&head,8);
   append(&head,15);
   append(&head,22);
   append(&head,5);
   append(&head,1);
   append(&head,45);
   append(&head,35);
   append(&head,6);
   append(&head,19);
   append(&head,33);
   append(&head,26);
   append(&head,14);

   treelink(head,headlink);
   display(headlink);

}
void display(struct node *q)
{
    struct node *current=q->next;
      while(current!=q)
      {
         printf(" %d ",current->data);
        current=current->next;
       }
}



void append(struct tree **q,int n)
{
   struct tree *current,*temp,*parent;
     if(*q==NULL)
      {
           temp=(struct tree*) malloc(sizeof(struct tree));
           temp->data=n;
           temp->left=NULL;
           temp->right=NULL;
          *q=temp;
       }
    else
     {
         current=*q;
        temp=(struct tree*) malloc(sizeof(struct tree));
       temp->data=n;
      temp->left=NULL;
      temp->right=NULL;
     while(current!=NULL)
      {
            parent=current;
            if(n<=current->data)
            current=current->left;
          else
            current=current->right;
        }
     if(n<=parent->data)
     parent->left=temp;
     else
      parent->right=temp;
      }
}

void treelink(struct tree *q,struct node *a)
{
    if(q==NULL)
    return;
    treelink(q->left,a);
    insertlink(a,q->data);
   treelink(q->right,a);
}

void insertlink(struct node *a,int i)
{
   struct node *current=a,*temp;
   while(current->next!=a)
   current=current->next;
   temp=(struct node*) malloc(sizeof(struct node));
   current->next=temp;
   temp->data=i;
   temp->prev=current;
   temp->next=a;
   a->prev=temp;
}

No comments: