Convert Sorted Array to Binary Search Tree

/**
 * 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) {
        return sortedArrToBST(nums, 0, nums.size() - 1);
    }

    TreeNode *sortedArrToBST(vector<int> &arr, int l, int r){
        if(l > r)   return NULL;
        //if(l == r)  return new TreeNode(arr[l]);

        int mid = (l+r)>>1;
        TreeNode *root = new TreeNode(arr[mid]);
        root->left = sortedArrToBST(arr, l, mid - 1);
        root->right = sortedArrToBST(arr, mid + 1, r);

        return root;
    }
};

results matching ""

    No results matching ""