Convert Sorted List to Binary Search Tree

描述

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

分析

这题与上一题类似,但是单链表不能随机访问,而自顶向下的二分法必须需要RandomAccessIterator,因此前面的方法不适用本题。

存在一种自底向上(bottom-up)的方法,见 http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

分治法,自顶向下

分治法,类似于 Convert Sorted Array to Binary Search Tree,自顶向下,复杂度 O(nlogn)

  1. // Convert Sorted List to Binary Search Tree
  2. // 二分法,类似于 Convert Sorted Array to Binary Search Tree,
  3. // 自顶向下,时间复杂度O(nlogn),空间复杂度O(logn)
  4. class Solution {
  5. public:
  6. TreeNode* sortedListToBST (ListNode* head) {
  7. if(head == nullptr) return nullptr;
  8. if(head->next == nullptr) return new TreeNode(head->val);
  9. ListNode *mid = cutAtMiddle(head);
  10. TreeNode *root = new TreeNode(mid->val);
  11. root->left = sortedListToBST(head);
  12. root->right = sortedListToBST(mid->next);
  13. return root;
  14. }
  15. ListNode* cutAtMiddle(ListNode *head) {
  16. if(head == nullptr) return nullptr;
  17. ListNode *fast = head;
  18. ListNode *slow = head;
  19. ListNode *prev_slow = head;
  20. while(fast != nullptr && fast->next != nullptr){
  21. prev_slow = slow;
  22. slow = slow->next;
  23. fast = fast->next->next;
  24. }
  25. prev_slow->next = nullptr;
  26. return slow;
  27. }
  28. };

自底向上

  1. // Convert Sorted List to Binary Search Tree
  2. // bottom-up,时间复杂度O(n),空间复杂度O(logn)
  3. class Solution {
  4. public:
  5. TreeNode *sortedListToBST(ListNode *head) {
  6. int len = 0;
  7. ListNode *p = head;
  8. while (p) {
  9. len++;
  10. p = p->next;
  11. }
  12. return sortedListToBST(head, 0, len - 1);
  13. }
  14. private:
  15. TreeNode* sortedListToBST(ListNode*& list, int start, int end) {
  16. if (start > end) return nullptr;
  17. int mid = start + (end - start) / 2;
  18. TreeNode *leftChild = sortedListToBST(list, start, mid - 1);
  19. TreeNode *parent = new TreeNode(list->val);
  20. parent->left = leftChild;
  21. list = list->next;
  22. parent->right = sortedListToBST(list, mid + 1, end);
  23. return parent;
  24. }
  25. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/binary-tree/bst/convert-sorted-list-to-binary-search-tree.html