Share my cpp solution


  • 0
    Z
      class Solution {
     public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size()==0)
    		return NULL;
    	
    	int size = nums.size();
    	TreeNode* root = new TreeNode(0);
    	
    	root->val = nums[(size)/2];
    	root->left = BuildTree(nums,0,(size)/2-1); 
    	root->right = BuildTree(nums,(size)/2+1,size-1);
    	
    	return root;
    }
    
    TreeNode* BuildTree(vector<int>& nums, int p,int q){
    	TreeNode* root = new TreeNode(0);
    	if(p>q)
    	return NULL;
    	
    	if(p==q){
    		root->val = nums[p];
    		return root;
    	}
    	
    	root->val = nums[(p+q+1)/2];
    	root->left = BuildTree(nums,p,(p+q+1)/2-1); 
    	root->right = BuildTree(nums,(p+q+1)/2+1,q);
    	return root;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.