Saturday, September 20, 2014

LeetCode: Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 /**  
  * Definition for singly-linked list.  
  * struct ListNode {  
  *   int val;  
  *   ListNode *next;  
  *   ListNode(int x) : val(x), next(NULL) {}  
  * };  
  */  

 /**  
  * Definition for binary tree  
  * struct TreeNode {  
  *   int val;  
  *   TreeNode *left;  
  *   TreeNode *right;  
  *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
  * };  
  */  

   TreeNode *sortedListToBST(ListNode *head) {  
     if(!head)return NULL;  
     TreeNode *root = new TreeNode(head->val);  
     if(!head->next)return root;  
     ListNode *fast = head->next, *slow = head, *prev;  
     while(fast)  
     {  
       prev = slow;  
       slow = slow->next;  
       if(fast->next)  
         fast = fast->next->next;  
       else fast = fast->next;  
     }  
     root->val = slow->val;  
     prev->next = NULL;  
     root->left = sortedListToBST(head);  
     root->right = sortedListToBST(slow->next);  
     return root;  
   }  

No comments:

Post a Comment