码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 108 Convert Sorted Array to Binary Search Tree

时间:2016-06-23 23:52:58      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

题目连接

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

Convert Sorted Array to Binary Search Tree

Description

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) {
        int n = 0;
        if(!(n = nums.size())) return nullptr;
        nums.insert(nums.begin(), 0);
        function<TreeNode*(int , int)> built = [&](int l, int r)->TreeNode* {
            if(l > r) return nullptr;
            int m = (l + r) >> 1;
            TreeNode *x = new TreeNode(nums[m]);
            x->left = built(l, m - 1);
            x->right = built(m + 1, r);
            return x;
        };
        return built(1, n);
    }
};

leetcode 108 Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/GadyPu/p/5612431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!