天天看点

LeetCode : Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

/**
 * 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) {
        if(nums.size()==)
            return NULL;
        if(nums.size()==)
            return new TreeNode(nums[]);
        int mid = nums.size()/;
        vector<int>vleft(nums.begin(),nums.begin()+mid);
        vector<int>vright(nums.begin()+mid+,nums.end());
        TreeNode *T = new TreeNode(nums[mid]);
        T->left = sortedArrayToBST(vleft);
        T->right = sortedArrayToBST(vright);
        return T;
    }
};