题目:给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
样例
给出数组 [1,2,3,4,5,6,7]
, 返回
4
/ \
2 6
/ \ / \
1 3 5 7
代码:
class Solution {
public:
/**
* @param A: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.size()==0) return NULL;
int start=0;
int end=A.size()-1;
int mid=(start+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=sort(A,start,mid-1);
root->right=sort(A,mid+1,end);
return root;
}
TreeNode *sort(vector<int> &A,int start,int end)
{ if(start>end) return NULL;
int mid=(start+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=sort(A,start,mid-1);
root->right=sort(A,mid+1,end);
return root;
}
};
感想:这个题一开始实在是不太懂,在网上看了很多别人的,才弄懂了一些。因为要创建一颗高度最小的二叉树,所以要使左右子树的节点数尽量相等,然后利用二分的思想,把数组从中分开,最中间的节点为根节点,然后创建出整个树。