Sorted Linked List to Balanced BST

PROBLEM :

Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List.

Examples:

Input:  Linked List 1->2->3
Output: A Balanced BST
     2  
   /  \
  1    3


Input: Linked List 1->2->3->4->5->6->7
Output: A Balanced BST
        4
      /   \
     2     6
   /  \   / \
  1   3  4   7

Input: Linked List 1->2->3->4
Output: A Balanced BST
      3  
    /  \
   2    4
 /
1

Input:  Linked List 1->2->3->4->5->6
Output: A Balanced BST
      4  
    /   \
   2     6
 /  \   /
1   3  5  

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*
typedef struct BST
{
int info ;
struct BST *left ;
struct BST *right ;
}tree ;

typedef struct NODE
{
int data ;
struct NODE *next ;
}node ;---------------------------------------------*/


tree* create_linklist_tree(node *head)
{
node *slow,*fast,*left,*right ;
tree *temp ;

if(head==NULL)
return NULL  ;

slow=head ;
fast=head->next ;

while(fast!=NULL&&fast->next!=NULL)
{
slow=slow->next ;
fast=fast->next->next ;
}

right=slow->next ;
slow->next=NULL ;

left=head ;

if(head!=slow)
while(left->next!=slow)
left=left->next ;
left->next=NULL ;

temp=(tree*)malloc(sizeof(tree)) ;
temp->info=slow->data ;

if(temp->info==head->data)
{
if(right==NULL)
temp->right=create_linklist_tree(NULL) ;
else
temp->right=create_linklist_tree(right) ;
temp->left=create_linklist_tree(NULL) ;
}
else
{
temp->right=create_linklist_tree(right) ;
temp->left=create_linklist_tree(head) ;
}

return temp ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )