leetcode之convert-sorted-array-to-binary-search-tree(将递增数组转化为BST搜索二叉树)
题目
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意
给定一个递增的连续数组,将其转化为一个BST搜索二叉树。
解题思路
这里直接采用递归,通过(start+end+1)/2快速获取到对应的中间index ,然后递归执行,其左子树为递归左边半个数组,右子树递归右边半个数组.
C++实现代码
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
return toBST(num,0,num.size()-1);
}
TreeNode* toBST(vector<int> &num,int start,int end){
if(start > end)
return nullptr;
int medelIndex = (start+end+1)/2;
TreeNode* tree = new TreeNode(num[medelIndex]);
tree->left = toBST(num,start,medelIndex-1);
tree->right = toBST(num,medelIndex+1,end);
return tree;
}
};