思路1.链表转数组

先将有序链表转化成数组,然后再将数组转换成二叉搜索树,类似Leetcode 108. 将有序数组转换成二叉搜索树
时间复杂度:Leetcode 109. 有序链表转换成二叉搜索树 - 图1, 空间复杂度:Leetcode 109. 有序链表转换成二叉搜索树 - 图2

思路2.

利用快慢指针求得链表中点做根节点,然后递归构成二叉搜索树
时间复杂度:Leetcode 109. 有序链表转换成二叉搜索树 - 图3, 空间复杂度:Leetcode 109. 有序链表转换成二叉搜索树 - 图4

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. /**
  12. * Definition for a binary tree node.
  13. * struct TreeNode {
  14. * int val;
  15. * TreeNode *left;
  16. * TreeNode *right;
  17. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  18. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  19. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  20. * };
  21. */
  22. class Solution {
  23. public:
  24. TreeNode* sortedListToBST(ListNode* head) {
  25. if(head==NULL) return NULL;
  26. if(head->next==NULL) return new TreeNode(head->val);
  27. ListNode *pre = head, *fast = head, *slow = head;
  28. while(fast&&fast->next){
  29. pre = slow;
  30. slow = slow->next;
  31. fast = fast->next->next;
  32. }
  33. pre->next = NULL;
  34. TreeNode* root = new TreeNode(slow->val);
  35. root->left = sortedListToBST(head);
  36. root->right = sortedListToBST(slow->next);
  37. return root;
  38. }
  39. };

思路3. 中序遍历优化

时间瓶颈是求中间结点,可以使用一个占位符先占用,使用中序遍历的思路,等到了该结点然后再填充上
时间复杂度:Leetcode 109. 有序链表转换成二叉搜索树 - 图5 空间复杂度:Leetcode 109. 有序链表转换成二叉搜索树 - 图6

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. /**
  12. * Definition for a binary tree node.
  13. * struct TreeNode {
  14. * int val;
  15. * TreeNode *left;
  16. * TreeNode *right;
  17. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  18. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  19. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  20. * };
  21. */
  22. class Solution {
  23. public:
  24. int getLength(ListNode* head){
  25. int len = 0;
  26. while(head){
  27. len++;
  28. head = head->next;
  29. }
  30. return len;
  31. }
  32. TreeNode* sortedListToBST(ListNode* head) {
  33. int len = getLength(head);
  34. return buildTree(head,0,len-1);
  35. }
  36. TreeNode* buildTree(ListNode*& head, int start, int end){
  37. if(start>end) return NULL;
  38. int mid = (start+end)>>1;
  39. TreeNode * root = new TreeNode();
  40. root->left = buildTree(head,start,mid-1);
  41. root->val = head->val;
  42. head = head->next;
  43. root->right = buildTree(head,mid+1,end);
  44. return root;
  45. }
  46. };