[Leetcode] Convert Sorted List to Binary Search Tree
Convert Sorted List to Binary Search Tree 题解
题目来源:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
Description
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
Solution
class Solution {
private:
struct Task {
TreeNode **nodep;
int start, end;
Task(TreeNode **p, int s, int e) :
nodep(p), start(s), end(e) {}
};
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.empty())
return NULL;
TreeNode *root, *node;
int start, end, mid;
queue<Task> q;
q.push(Task(&root, 0, nums.size() - 1));
while (!q.empty()) {
Task task = q.front();
q.pop();
start = task.start;
end = task.end;
if (start > end)
continue;
mid = (start + end) / 2;
node = new TreeNode(nums[mid]);
*(task.nodep) = node;
if (start == end)
continue;
q.push(Task(&(node -> left), start, mid - 1));
q.push(Task(&(node -> right), mid + 1, end));
}
return root;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
if (!head)
return NULL;
vector<int> nums;
while (head) {
nums.push_back(head -> val);
head = head -> next;
}
return sortedArrayToBST(nums);
}
};
解题描述
这道题题意是将一个数据已经排好序的链表转换成一个平衡BST。上面给出的解法是先将链表数据读到一个数组中再对数组进行平衡BST构造。这样的话在二分阶段数据访问速度较快,但是明显的问题在于当链表中的数据量非常大的时候会非常占据内存空间。
针对这个问题下面给出的是直接对链表进行二分的解法,当然时间复杂度会较高,原来对数组进行操作的话是O(n * log n),直接对链表进行二分的话是O(n * n * log n)。
class Solution {
private:
TreeNode* listToTree(ListNode *start, ListNode *end) {
if (start == end)
return NULL;
if (start -> next == end)
return new TreeNode(start -> val);
ListNode *mid = start, *tail = start;
while (tail != end && tail -> next != end) {
mid = mid -> next;
tail = tail -> next -> next;
}
TreeNode *node = new TreeNode(mid -> val);
node -> left = listToTree(start, mid);
node -> right = listToTree(mid -> next, end);
return node;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
return listToTree(head, NULL);
}
};