您的位置:首页 > 编程语言 > C语言/C++

177.把排序数组转换为高度最小的二叉搜索树

2017-04-23 16:26 232 查看
题目:给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

样例

给出数组 
[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;
}
};
感想:这个题一开始实在是不太懂,在网上看了很多别人的,才弄懂了一些。因为要创建一颗高度最小的二叉树,所以要使左右子树的节点数尽量相等,然后利用二分的思想,把数组从中分开,最中间的节点为根节点,然后创建出整个树。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++作业