面试题 04.02. 最小高度树
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-height-tree-lcci/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
参考链接:图解递归构造平衡二叉搜索树 C++
/**
* 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* dfs(vector<int>& nums, int left, int right) {
if(left > right) return nullptr;
int mid = (left+right)>>1;//为什么用位运算
cout << mid<<endl;
TreeNode* root = new TreeNode(nums[mid]);
root->left = dfs(nums, left, mid - 1);
root->right = dfs(nums, mid + 1, right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return dfs(nums, 0, nums.size() - 1);
}
};