[LeetCode] 109. Convert Sorted List to Binary Search Tree

别说谁变了你拦得住时间么 提交于 2020-02-11 04:03:55

将有序链表转化为二叉搜索树。题目即是题意,跟[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 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!