From 7a5e03d22723a8ddcb7bfccd28a6a059c45b408e Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Thu, 6 Mar 2025 00:17:49 +0800 Subject: [PATCH] feat: 109_convert_sorted_list_to_binary_search_tree --- .../main.cpp | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 109_convert_sorted_list_to_binary_search_tree/main.cpp diff --git a/109_convert_sorted_list_to_binary_search_tree/main.cpp b/109_convert_sorted_list_to_binary_search_tree/main.cpp new file mode 100644 index 0000000..00e42c0 --- /dev/null +++ b/109_convert_sorted_list_to_binary_search_tree/main.cpp @@ -0,0 +1,59 @@ +#include +using namespace std; + +struct ListNode { + int val; + ListNode *next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode *next) : val(x), next(next) {} +}; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { + public: + TreeNode *sortedListToBST(ListNode *head) { + if (!head) return nullptr; + + vector nums; + + ListNode *currentNode = head; + while (currentNode) { + nums.emplace_back(currentNode->val); + currentNode = currentNode->next; + } + + TreeNode *root = new TreeNode(); + appendArrayToNode(nums, root); + return root; + } + + void appendArrayToNode(vector &nums, TreeNode *root) { + int mid = nums.size() / 2; + root->val = nums[mid]; + + if (nums.size() == 1) return; + + vector leftNums, rightNums; + copy(nums.begin(), nums.begin() + mid, back_inserter(leftNums)); + copy(nums.begin() + mid + 1, nums.end(), back_inserter(rightNums)); + + if (!leftNums.empty()) { + root->left = new TreeNode(); + appendArrayToNode(leftNums, root->left); + } + + if (!rightNums.empty()) { + root->right = new TreeNode(); + appendArrayToNode(rightNums, root->right); + } + } +}; \ No newline at end of file