1、最小高度二叉搜索树(面试题 04.02)
首先确定递归 DFS
递归出口:l > r
创建根节点
1 填值,注意mid = (r - l)/2 + l
2 创建左子树和右子树 DFS(nums, l, mid-1)和DFS(nums, mid+1, r)
class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { return DFS(nums, 0, nums.size()-1); } TreeNode* DFS(vector<int>& nums, int l, int r){ if(l>r){return nullptr;} TreeNode* root = new TreeNode(); int mid = (r-l)/2 + l; root->val = nums[mid]; root->left = DFS(nums, l, mid-1); root->right = DFS(nums, mid+1, r); return root; } };