码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-11 10:10:48      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:ssi   get   href   obs   search   listt   represent   wing   时间   

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

 

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

标签:ssi   get   href   obs   search   listt   represent   wing   时间   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12293684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!