Leetcode 108 Solution

This article provides solution to leetcode question 108 (convert-sorted-array-to-binary-search-tree)

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums, int s, int e) {
        if (s > e)
            return NULL;

        if (s == e)
            return new TreeNode(nums[s]);

        int m = (s + e) / 2;

        TreeNode* node = new TreeNode(nums[m]);
        node->left = sortedArrayToBST(nums, s, m - 1);
        node->right = sortedArrayToBST(nums, m + 1, e);

        return node;
    }

    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if (nums.size() == 0)
            return NULL;

        return sortedArrayToBST(nums, 0, nums.size() - 1);
    }
};