4/18/2014

Leetcode -- Convert Sorted List to Binary Search Tree

Overtime
 /**  
  * 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) {}  
  * };  
  */  
 class Solution {  
 public:  
   TreeNode *sortedListToBST(ListNode *head) {  
     if(head == NULL) {  
       return NULL;  
     }  
     int listSize = 0;  
     ListNode * p = head;  
     while(p != NULL) {  
       listSize++;  
       p = p->next;  
     }  
     return sortedListToBSTHelper(head, 0, listSize - 1);  
   }  
   TreeNode * sortedListToBSTHelper(ListNode * head, int start, int end) {  
     if(start > end) {  
       return NULL;  
     }  
     int middle = (start + end) /2;  
     ListNode * p = head;  
     for(int i = 0; i < middle; ++i) {  
       p = p->next;  
     }  
     TreeNode * newNode = new TreeNode(p->val);  
     newNode->left = sortedListToBSTHelper(head, start, middle - 1);  
     newNode->right = sortedListToBSTHelper(head, middle + 1, end);  
     return newNode;  
   }  
 };  

No comments: