思路:对于当前数组,去元素位置的中位数作为根节点,左右两端的元素分别构造子树,就能构造一颗平衡二叉树。
code:
class Solution {
public:
TreeNode * buildBST(vector<int>::iterator beginIt, int num){
vector<int>::iterator it = beginIt + num/2;
TreeNode *root = new TreeNode(*it);
if(it > beginIt)
root->left = buildBST(beginIt,num/2);
if(it < beginIt + num - 1)
root->right = buildBST(it+1,num - num/2 - 1);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
TreeNode * root;
if(num.size()>0)
return buildBST(num.begin(),num.size());
}
};
本文介绍了一种将有序数组转换为平衡二叉搜索树的方法。通过选取数组中间元素作为根节点,并递归地对左右子数组进行相同操作来构建平衡树。这种方法确保了树的高度尽可能小。
1349

被折叠的 条评论
为什么被折叠?



