Problem
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Example
Input:[1,2,3]
Output:
1
/\
2 3
Algorithm
整理一下题意:给定一个升序数组,要求将其转化为一课平衡二叉树
经典的树类型题目。采用DFS思路解决。对于某个节点,左子树的值均小于该节点,右子树的值均大于该节点。于是递归左子树和右子树即可得到整棵树。由于要求平衡,取数组中值为根节点。代码如下。
//DFS
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0) return NULL;
return convert(nums,0,nums.size()-1);
}
TreeNode* convert(vector<int>& nums,int begin,int end){
if(begin>end) return NULL;
int mid=(begin+end)/2;
TreeNode* p=new TreeNode(nums[mid]);
p->left=convert(nums,begin,mid-1);
p->right=convert(nums,mid+1,end);
return p;
}
};