nikunjsoni

108

Jul 26th, 2021
122
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() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.     TreeNode* sortedArrayToBST(vector<int>& nums) {
  15.         return toBST(nums, 0, nums.size()-1);
  16.     }
  17.    
  18.     TreeNode* toBST(vector<int> &nums, int left, int right){
  19.         if(left>right) return NULL;
  20.         int mid = (left+right)/2;
  21.         TreeNode *node = new TreeNode(nums[mid]);
  22.         node->left = toBST(nums, left, mid-1);
  23.         node->right = toBST(nums, mid+1, right);
  24.         return node;
  25.     }
  26.    
  27. };
RAW Paste Data