s0108
This commit is contained in:
parent
968e8f3adc
commit
b2e4f6daad
15
include/s0108_convert_sorted_array_to_binary_search_tree.hpp
Normal file
15
include/s0108_convert_sorted_array_to_binary_search_tree.hpp
Normal 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
|
@ -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 。数组中点为根节点,中点左侧部分生成左子树,右侧部分生成右子树,递归。
|
||||
|
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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user