s0108
This commit is contained in:
18
src/s0108_convert_sorted_array_to_binary_search_tree.cpp
Normal file
18
src/s0108_convert_sorted_array_to_binary_search_tree.cpp
Normal file
@@ -0,0 +1,18 @@
|
||||
#include "s0108_convert_sorted_array_to_binary_search_tree.hpp"
|
||||
|
||||
TreeNode* sortedArrayToBSTHelper(vector<int>& nums, int begin, int end) {
|
||||
// 找到 nums 的中点
|
||||
int middle = (begin + end) >> 1;
|
||||
// 创建根节点
|
||||
TreeNode *root = new TreeNode(nums[middle]);
|
||||
// 左子树
|
||||
if (middle != begin) root->left = sortedArrayToBSTHelper(nums, begin, middle - 1);
|
||||
// 右子树
|
||||
if (middle != end) root->right = sortedArrayToBSTHelper(nums, middle + 1, end);
|
||||
// 返回根节点
|
||||
return root;
|
||||
}
|
||||
|
||||
TreeNode* S0108::sortedArrayToBST(vector<int>& nums) {
|
||||
return sortedArrayToBSTHelper(nums, 0, nums.size() - 1);
|
||||
}
|
Reference in New Issue
Block a user