题解 | #将升序数组转化为平衡二叉搜索树# | C++
将升序数组转化为平衡二叉搜索树
https://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <vector> class Solution { private: TreeNode* dfs(const vector<int>& nums, int b, int e) { if (b > e) { return nullptr; } int mid = b + (e - b)/2 + (e-b)%2; TreeNode* node = new TreeNode(nums[mid]); node->left = dfs(nums, b, mid-1); node->right = dfs(nums, mid+1, e); return node; } public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型vector * @return TreeNode类 */ TreeNode* sortedArrayToBST(vector<int>& nums) { return dfs(nums, 0, nums.size()-1); } };