题目

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

  1. Given the sorted linked list: [-10,-3,0,5,9],
  2. One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
  3. 0
  4. / \
  5. -3 9
  6. / /
  7. -10 5

题意

将一个有序链表转换成左右子树高度差不超过1的平衡二叉查找树。

思路

比较简单的方法是,将链表中的值存入数组中,接下来与 108. Convert Sorted Array to Binary Search Tree 一样进行二分递归。

直接用快慢指针可以一次遍历找到链表中的中位数:初始时快慢指针同时指向头结点,每次移动慢指针走1步、快指针走2步,当快指针无法继续走时慢指针正好指在中位数处。每次找到当前链表的中位数作为当前子树的根,以中位数为中心划分出左右链表,递归生成左右子树。

模拟中序遍历:很玄妙,利用了二叉查找树的中序遍历是递增序列的性质,具体还是看官方解答 - Approach 3: Inorder Simulation


代码实现

Java

快慢指针

  1. class Solution {
  2. public TreeNode sortedListToBST(ListNode head) {
  3. if (head == null) {
  4. return null;
  5. }
  6. ListNode mid = findMid(head);
  7. TreeNode x = new TreeNode(mid.val);
  8. x.left = mid == head ? null : sortedListToBST(head);
  9. x.right = sortedListToBST(mid.next);
  10. return x;
  11. }
  12. private ListNode findMid(ListNode head) {
  13. ListNode pre = null;
  14. ListNode slow = head, fast = head;
  15. while (fast.next != null && fast.next.next != null) {
  16. pre = slow;
  17. slow = slow.next;
  18. fast = fast.next.next;
  19. }
  20. if (pre != null) {
  21. pre.next = null;
  22. }
  23. return slow;
  24. }
  25. }

模拟中序遍历

  1. class Solution {
  2. private ListNode head;
  3. public TreeNode sortedListToBST(ListNode head) {
  4. this.head = head;
  5. // 求出链表长度
  6. int len = 0;
  7. ListNode p = head;
  8. while (p != null) {
  9. len++;
  10. p = p.next;
  11. }
  12. return sortedListToBST(0, len - 1);
  13. }
  14. private TreeNode sortedListToBST(int left, int right) {
  15. if (left > right) {
  16. return null;
  17. }
  18. int mid = (left + right) / 2;
  19. TreeNode leftChild = sortedListToBST(left, mid - 1);
  20. TreeNode root = new TreeNode(head.val);
  21. root.left = leftChild;
  22. head = head.next;
  23. root.right = sortedListToBST(mid + 1, right);
  24. return root;
  25. }
  26. }

JavaScript

  1. /**
  2. * @param {ListNode} head
  3. * @return {TreeNode}
  4. */
  5. var sortedListToBST = function (head) {
  6. const nums = []
  7. while (head) {
  8. nums.push(head.val)
  9. head = head.next
  10. }
  11. return dfs(nums, 0, nums.length - 1)
  12. }
  13. var dfs = function (nums, left, right) {
  14. if (left > right) return null
  15. const mid = Math.trunc((right - left) / 2) + left
  16. const root = new TreeNode(nums[mid])
  17. root.left = dfs(nums, left, mid - 1)
  18. root.right = dfs(nums, mid + 1, right)
  19. return root
  20. }