SHARE
TWEET

Untitled

bbescos Mar 7th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Solution {
  11. public:
  12.    
  13.     void printVector(const vector<int>& vec) {
  14.         for(int num : vec)
  15.             std::cout << num << " ";
  16.        
  17.         std::cout << std::endl;
  18.     }
  19.    
  20.     TreeNode* createTree(const vector<int>& nums, int start, int end) {
  21.        
  22.         if (start > end)
  23.             return nullptr;
  24.        
  25.         int middle = start + (end - start) / 2;
  26.         TreeNode* node = new TreeNode(nums[middle]);
  27.        
  28.         node->left = createTree(nums, start, middle - 1);
  29.         node->right = createTree(nums, middle + 1, end);
  30.            
  31.         return node;
  32.     }
  33.    
  34.     TreeNode* sortedArrayToBST(vector<int>& nums) {
  35.        
  36.         if (nums.size() == 0)
  37.             return nullptr;
  38.        
  39.         return createTree(nums, 0, nums.size() - 1);
  40.     }
  41. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top