108. Convert Sorted Array to Binary Search Tree
problem description
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 every node 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
algorithm thought
这里需要生成一个平衡BST。平衡BST有很多种表示方法,但是我们只需要生成一种就行,那当然是生成最简单的bst。每次到一个节点时,找到中点,将一个有序数组对分。直到叶节点。这样就能保证最后得到的是平衡二叉树
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
时间复杂度应该是O(n)遍历到所有节点,最后生成一个树
Last updated