6/07/2014

Leetcode -- Convert Sorted List to Binary Search Tree

 /**  
  * 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;  
     }  
     // check the length of the list node  
     ListNode * p = head;  
     int length = 0;  
     while(p != NULL) {  
       length++;  
       p = p->next;  
     }  
     return sortedListToBST(head, 0, length - 1);  
   }  
   TreeNode * sortedListToBST(ListNode *& head, int start, int end) {  
     if(start > end) {  
       return NULL;  
     }  
     int mid = start + (end - start) / 2;  
     TreeNode * left = sortedListToBST(head, start, mid - 1);  
     TreeNode * parent = new TreeNode(head->val);  
     parent->left = left;  
     head = head->next;  
     parent->right = sortedListToBST(head, mid + 1, end);  
     return parent;  
   }  
 };  

No comments: