将有序链表转化为二叉搜索树。题目即是题意,跟[LeetCode] 108. Convert Sorted Array to Binary Search Tree可以一起做。108是从有序数组转化成BST,109是从有序链表转化成BST。区别在于108可以通过找中点的办法快速找到根节点,但是109只能通过快慢指针的办法找到根节点。例子,
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
时间O(n)
空间O(n)
1 /** 2 * @param {ListNode} head 3 * @return {TreeNode} 4 */ 5 var sortedListToBST = function (head) { 6 if (head === null) return null; 7 return helper(head, null); 8 }; 9 10 var helper = function (head, tail) { 11 if (head === tail) return null; 12 let slow = head; 13 let fast = head; 14 while (fast !== tail && fast.next !== tail) { 15 fast = fast.next.next; 16 slow = slow.next; 17 } 18 let root = new TreeNode(slow.val); 19 root.left = helper(head, slow); 20 root.right = helper(slow.next, tail); 21 return root; 22 }
来源:https://www.cnblogs.com/aaronliu1991/p/12293684.html