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

时间:2025-01-22 12:03:20

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

给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

注意事项

There may exist multiple valid solutions, return any of them.

您在真实的面试中是否遇到过这个题?
Yes
哪家公司问你的这个题? LinkedIn Airbnb Amazon Cryptic Studios Dropbox Epic Systems TinyCo Hedvig Facebook Google Uber Yelp Apple Yahoo Bloomberg Zenefits Twitter Microsoft Snapchat
感谢您的反馈
样例

给出数组 [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: an integer array
* @return: A tree node
*/
TreeNode * sortedArrayToBST(vector<int> &A) {
// write your code here
if(!A.size())
return NULL;
int r=A.size()-1;
int l=0;
int m=(l+r)>>1;
TreeNode *root=subNode(A,l,r);
return root;
}
TreeNode *subNode(vector<int> A,int l,int r)
{
if(l>r)
return NULL;
int m=(l+r)>>1;
TreeNode *root=new TreeNode(A[m]);
root->left=subNode(A,l,m-1);
root->right=subNode(A,m+1,r);
return root;
}
};