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

Given the head of 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:

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [0]
Output: [0]

Example 4:

Input: head = [1,3]
Output: [3,1]

Constraints:

  • The number of nodes in head is in the range [0, 2 * 104].
  • -10^5 <= Node.val <= 10^5

有序链表转换二叉搜索树。

给定一个单链表的头节点  head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差不超过 1。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目即是题意,可以跟108题一起做。108是从有序数组转化成BST,109是从有序链表转化成BST。区别在于108可以通过找中点的办法快速找到根节点,但是109只能通过快慢指针的办法找到根节点,思路都是递归。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public TreeNode sortedListToBST(ListNode head) {
 3         if (head == null)
 4             return null;
 5         return helper(head, null);
 6     }
 7 
 8     public TreeNode helper(ListNode head, ListNode tail) {
 9         if (head == tail)
10             return null;
11         ListNode slow = head;
12         ListNode fast = head;
13         while (fast != tail && fast.next != tail) {
14             fast = fast.next.next;
15             slow = slow.next;
16         }
17         TreeNode root = new TreeNode(slow.val);
18         root.left = helper(head, slow);
19         root.right = helper(slow.next, tail);
20         return root;
21     }
22 }

 

JavaScript实现

 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 }

 

相关题目

108. Convert Sorted Array to Binary Search Tree

109. Convert Sorted List to Binary Search Tree

1382. Balance a Binary Search Tree

LeetCode 题目总结

posted @ 2020-02-11 03:08  CNoodle  阅读(460)  评论(0编辑  收藏  举报