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

108. Convert Sorted Array to Binary Search Tree

时间:2017-10-02 20:54:36      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:log   class   roo   build   ted   int   root   nod   treenode   

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* build(vector<int>& nums,int begin, int end){
        if(begin>end)return NULL;
        int mid=(begin+end)/2;
        TreeNode *root = new TreeNode(nums[mid]);
        root->left=build(nums,begin,mid-1);
        root->right=build(nums,mid+1,end);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.empty())return {};
        return build(nums,0,nums.size()-1);
    }
};

 

108. Convert Sorted Array to Binary Search Tree

标签:log   class   roo   build   ted   int   root   nod   treenode   

原文地址:http://www.cnblogs.com/tsunami-lj/p/7622239.html

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