4/20/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) {  
     std::vector<int> sortedNums;  
     populateSortedVector(head, sortedNums);  
     return constructBST(sortedNums, 0, sortedNums.size() - 1);  
   }  
   void populateSortedVector(ListNode * head, std::vector<int>& sortedNums) {  
     for(ListNode * p = head; p != NULL; p = p->next) {  
       sortedNums.emplace_back(p->val);  
     }  
   }  
   TreeNode * constructBST(std::vector<int>& sortedNums, int start, int end) {  
     if(start > end) {  
       return NULL;  
     }  
     int mid = (start + end) / 2;  
     TreeNode * root = new TreeNode(sortedNums[mid]);  
     root->left = constructBST(sortedNums, start, mid - 1);  
     root->right = constructBST(sortedNums, mid + 1, end);  
     return root;  
   }  
 };  

No comments: