leetcode 108 Convert Sorted Array to Binary Search Tree

给定一个有序的数组,生成平衡二叉树。

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

TreeNode* sort(vector<int>& nums, int start, int end) {
    if (start > end)
        return NULL;
    
    int mid = (start + end) / 2;
    TreeNode* r = new TreeNode(nums[mid]);
    r->left = sort(nums, start, mid - 1);
    r->right = sort(nums, mid + 1, end);
    return r;
}

 

posted on 2018-01-24 01:48  willaty  阅读(78)  评论(0编辑  收藏  举报

导航