This commit is contained in:
Sainnhe Park 2023-02-01 12:14:24 +08:00
parent 968e8f3adc
commit b2e4f6daad
3 changed files with 34 additions and 0 deletions

View File

@ -0,0 +1,15 @@
#ifndef S0108_CONVERT_SORTED_ARRAY_TO_BINARY_SEARCH_TREE_HPP
#define S0108_CONVERT_SORTED_ARRAY_TO_BINARY_SEARCH_TREE_HPP
#include <vector>
#include "structures.hpp"
using namespace std;
class S0108 {
public:
TreeNode* sortedArrayToBST(vector<int>& nums);
};
#endif

View File

@ -4,3 +4,4 @@
- [s0701](https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/): 插入节点。一层一层往下找,直到发现找不到了就在这个地方插入。
- [s0450](https://leetcode.cn/problems/delete-node-in-a-bst/description/): 删除节点。递归删除。
- [s0669](https://leetcode.cn/problems/trim-a-binary-search-tree/description/): 修剪 BST 。递归修剪。
- [s0108](https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/): 有序数组转 BST 。数组中点为根节点,中点左侧部分生成左子树,右侧部分生成右子树,递归。

View 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);
}