109. 有序链表转换二叉搜索树

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. /**
  12. * Definition for a binary tree node.
  13. * public class TreeNode {
  14. * int val;
  15. * TreeNode left;
  16. * TreeNode right;
  17. * TreeNode() {}
  18. * TreeNode(int val) { this.val = val; }
  19. * TreeNode(int val, TreeNode left, TreeNode right) {
  20. * this.val = val;
  21. * this.left = left;
  22. * this.right = right;
  23. * }
  24. * }
  25. */
  26. class Solution {
  27. public TreeNode sortedListToBST(ListNode head) {
  28. if (head == null)
  29. return null;
  30. return dfs(head, null);
  31. }
  32. private TreeNode dfs(ListNode left, ListNode right) {
  33. if (left == right)
  34. return null;
  35. ListNode slow = left;
  36. ListNode fast = left;
  37. while (fast != right && fast.next != right) {
  38. fast = fast.next.next;
  39. slow = slow.next;
  40. }
  41. TreeNode root = new TreeNode(slow.val);
  42. // 这里是dfs(left, slow)是因为区间是[left, right)
  43. root.left = dfs(left, slow);
  44. root.right = dfs(slow.next, right);
  45. return root;
  46. }
  47. }