109. Convert Sorted List to Binary Search Tree
Đề Bài
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example 1:
Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = [] Output: []
Constraints:
- The number of nodes in
headis in the range[0, 2 * 104]. -105 <= Node.val <= 105
Thuật Toán & Kỹ Thuật
⏱️ Thời gian
O(log n)
💾 Không gian
O(n)
Lời Giải
C++
0109-convert-sorted-list-to-binary-search-tree.cpp
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
/**
* Definition for a binary tree node.
* 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 {
private:
vector<int> v;
public:
TreeNode *dfs(int left, int right) {
if (left > right) {
return nullptr;
}
int mid = (left + right) >> 1;
TreeNode *root = new TreeNode(v[mid]);
root->left = dfs(left, mid - 1);
root->right = dfs(mid + 1, right);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
while (head) {
v.push_back(head->val);
head = head->next;
}
return dfs(0, v.size() - 1);
}
};