题目
LeetCode - 108. Convert Sorted Array to Binary Search Tree
题目链接
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
参考博客
解题思路
此题属于基础题,递归解题即可。
解题源码
/**
* 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* f(vector<int> &h, int i, int j){
if (i > j) return nullptr;
int mid = (i+j+1) /2;
TreeNode *root = new TreeNode(h[mid]);
root->left = f(h, i, mid - 1);
root->right = f(h, mid + 1, j);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return f(nums, 0, nums.size() - 1);
}
};