108. Convert Sorted Array to Binary Search Tree
problem description
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 5algorithm thought
code
/**
* 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 build(nums,0,nums.size());
}
TreeNode* build(vector<int>& nums,int low,int high){
if(high==low)
return NULL;
int mid=low+((high-low)>>1);
//cout<<low<<'-'<<high<<' ';
TreeNode* root=new TreeNode(nums[mid]);
root->left=build(nums,low,mid);
root->right=build(nums,mid+1,high);
return root;
}
};algorithm analysis
Last updated