[LeetCode] 109. Convert Sorted List to Binary Search Tree
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 109. Convert Sorted List to Binary Search Tree相关的知识,希望对你有一定的参考价值。
将有序链表转化为二叉搜索树。题目即是题意,跟[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的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 109. Convert Sorted List to Binary Search Tree
Leetcode109. Convert Sorted List to Binary Search Tree
LeetCode-109-Convert Sorted List to Binary Search Tree
leetcode109. Convert Sorted List to Binary Search Tree