leetcode-108-Convert-Sorted-Array-to-Binary-Search-Tree

描述


Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

分析


非常简单的一道题,首先要搞清楚 BST,即二叉搜索树的概念,而给定的字符串又是拍过序的,用二分法即可。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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 arrayToBST(nums, 0, nums.size()-1);
}
TreeNode* arrayToBST(vector<int>& nums, int start, int end) {
if(start > end) {
return NULL;
}
int mid = start + (end-start)/2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = arrayToBST(nums, start, mid-1);
root->right = arrayToBST(nums, mid+1, end);
return root;
}
};

相关问题


(M) Convert Sorted List to Binary Search Tree

题目来源