# 【LeetCode & 剑指offer刷题】树题17：Convert Sorted Array to Binary Search Tree

【LeetCode & 剑指offer 刷题笔记】目录（持续更新中...）

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/  \
-3   9
/    /
-10  5

C++

/**
* 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 buildTree(nums,0,nums.size()-1); //注意索引从0开始
}

TreeNode* buildTree(vector<int>& nums, int start, int end)
{

if(start > end) return NULL; //递归子函数的出口（不能取等号，因为单个元素也要分配空间）

int mid = (start + end + 1)/2; //+1是为了向上取整，由于是升序排列，当(start+end)/2不为整数时，取较大的那个数作为根
TreeNode* root = new TreeNode(nums[mid]);   //构建根结点
root->left = buildTree(nums, start, mid-1); //构建左子树
root->right = buildTree(nums, mid+1, end); //构建右子树

return root; //递归原始母函数的出口，返回最顶层的根结点指针

}
};

posted @ 2019-01-05 19:50  wikiwen  阅读(175)  评论(0编辑  收藏