问题描述:
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
给出数组 [1,2,3,4,5,6,7]
, 返回
4
/ \
2 6
/ \ / \
1 3 5 7
写了一个返回值为TreeNode类型的函数,然后用二分法,建立新的搜索二叉树就ok了
实现代码:
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;
else
{
cmp(A,0,A.size()-1);
}
}
TreeNode* cmp(vector<int>&A,int left,int right)
{
if(left>right) return NULL ;
int mid=(left+right)/2;
TreeNode *root= new TreeNode(A[mid]);
root->left=cmp(A,left,mid-1);
root->right=cmp(A,mid+1,right);
return root;
}
};
感想:这题的技巧在于返回值为节点类型的函数,然后还要明白什么是搜索二叉树,最后还要懂得如何运用二分法建立树。