Leetcode面试题 04.02. 最小高度树
简单递归构造树,解答如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return buildTree(nums, 0, nums.size());
}
private:
TreeNode* buildTree(vector<int>& nums, int b, int e) {
if (b == e) return NULL;
int m = b + (e-b)/2;
TreeNode* root = new TreeNode(nums[m]);
root->left = buildTree(nums, b, m);
root->right = buildTree(nums, m+1, e);
return root;
}
};
另外,一直以来都有个问题:
如上述代码,若用b + (e-b)/2
代替所有m
,不知为何会出现执行出错