Share my C++ solution,easy to understand


  • 0
    V
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            int n = nums.size();
            if (n == 0)
                return NULL;
            
            TreeNode* root = createBST(nums, 0, n-1);
            
            return root;
        }
        
        TreeNode* createBST(vector<int>& nums, int left, int right)
        {
            if (left > right)
                return NULL;
            
            int mid = left + (right - left + 1) / 2;
            TreeNode *node = new TreeNode(nums[mid]);
            
            if (node != NULL)
            {
                node->left = createBST(nums, left, mid-1);
                node->right = createBST(nums, mid+1, right);
            }
            
            return node;
        }
    };

Log in to reply
 

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