From b2e4f6daaddf119c1b5342d9dcb627f6aa746f4e Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 1 Feb 2023 12:14:24 +0800 Subject: [PATCH] s0108 --- ...vert_sorted_array_to_binary_search_tree.hpp | 15 +++++++++++++++ notes/src/bstree.md | 1 + ...vert_sorted_array_to_binary_search_tree.cpp | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 include/s0108_convert_sorted_array_to_binary_search_tree.hpp create mode 100644 src/s0108_convert_sorted_array_to_binary_search_tree.cpp diff --git a/include/s0108_convert_sorted_array_to_binary_search_tree.hpp b/include/s0108_convert_sorted_array_to_binary_search_tree.hpp new file mode 100644 index 0000000..05c75c6 --- /dev/null +++ b/include/s0108_convert_sorted_array_to_binary_search_tree.hpp @@ -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 + +#include "structures.hpp" + +using namespace std; + +class S0108 { + public: + TreeNode* sortedArrayToBST(vector& nums); +}; + +#endif diff --git a/notes/src/bstree.md b/notes/src/bstree.md index 272308c..546fb4d 100644 --- a/notes/src/bstree.md +++ b/notes/src/bstree.md @@ -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 。数组中点为根节点,中点左侧部分生成左子树,右侧部分生成右子树,递归。 diff --git a/src/s0108_convert_sorted_array_to_binary_search_tree.cpp b/src/s0108_convert_sorted_array_to_binary_search_tree.cpp new file mode 100644 index 0000000..2397888 --- /dev/null +++ b/src/s0108_convert_sorted_array_to_binary_search_tree.cpp @@ -0,0 +1,18 @@ +#include "s0108_convert_sorted_array_to_binary_search_tree.hpp" + +TreeNode* sortedArrayToBSTHelper(vector& 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& nums) { + return sortedArrayToBSTHelper(nums, 0, nums.size() - 1); +}