一.题目描述
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
给出数组 [1,2,3,4,5,6,7]
, 返回
4
/ \
2 6
/ \ / \
1 3 5 7
找到排序数组中间的一个值给根节点,左子树的值比根节点小,右子树的值比根节点大,当左子树的值大于右子树时递归结束.
三.实现代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
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 {
return ff(A,0,A.size()-1);
}
}
TreeNode* ff(vector<int>&A,int left,int right){
if(left>right) return NULL;
int mid=(left+right)/2;
TreeNode *tree=new TreeNode(A[mid]);
tree->left=ff(A,left,mid-1);
tree->right=ff(A,mid+1,right);
return tree;
}
};
四.感悟
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
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 {
return ff(A,0,A.size()-1);
}
}
TreeNode* ff(vector<int>&A,int left,int right){
if(left>right) return NULL;
int mid=(left+right)/2;
TreeNode *tree=new TreeNode(A[mid]);
tree->left=ff(A,left,mid-1);
tree->right=ff(A,mid+1,right);
return tree;
}
};
做这道题主要是想不到将中间值作为根节点的实现代码.