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 TreeNode sortedListToBST (ListNode head) {
  6. if(head == null) return null;
  7. if(head.next == null) return new TreeNode(head.val);
  8. ListNode mid = cutAtMiddle(head);
  9. TreeNode root = new TreeNode(mid.val);
  10. root.left = sortedListToBST(head);
  11. root.right = sortedListToBST(mid.next);
  12. return root;
  13. }
  14. ListNode cutAtMiddle(ListNode head) {
  15. if(head == null) return null;
  16. ListNode fast = head;
  17. ListNode slow = head;
  18. ListNode prev_slow = head;
  19. while(fast != null && fast.next != null){
  20. prev_slow = slow;
  21. slow = slow.next;
  22. fast = fast.next.next;
  23. }
  24. prev_slow.next = null;
  25. return slow;
  26. }
  27. }

自底向上

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

相关题目

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