0%

leetCode-109:Convert Sorted List to Binary Search Tree

问题描述

给定一个升序的链表,要求将其转换成高度平衡的搜索二叉树。题目链接:**点我**

样例输入输出

输入:1->2->3

输出:

2

/ \

1 3

输入:1

输出:1

问题解法

此题跟 LeetCode-108类似,只不过前面是数组,这次是链表。解法类似,先找到中间的节点,然后拆分左子树和右子树,依次进行递归构造。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
return convert2BST(head, null);
}

private TreeNode convert2BST(ListNode left, ListNode right) {
if (left == right) {
return null;
}

ListNode fast = left;
ListNode slow = left;
while (fast != right && fast.next != right) {
fast = fast.next.next;
slow = slow.next;
}

TreeNode root = new TreeNode(slow.val);
root.left = convert2BST(left, slow);
root.right = convert2BST(slow.next, right);
return root;
}
}