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.

Solution:

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