Binary search tree with minimal height means: we want the root to be the middle of the array.
TreeNode* builder (vector<int>& nums, int start, int end){
if( start > end) return nullptr;
int idx = start+(end-start)/2;
TreeNode* root = new TreeNode(nums[idx]);
root->left = builder(nums, start, idx-1);
root->right = builder(nums, idx+1, end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
return builder(A, 0, A.size()-1);
}
本文介绍了一种从有序数组构建最小高度二叉搜索树的方法。通过递归选择中间元素作为根节点,并将左右子数组分别构建成左子树和右子树,确保了树的高度尽可能小。

435

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



