Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:此题与排序数组很大的不同是链表不知道长度以及上面的值。其整体思路还是中间值作为根节点,但是需要一点策略,不然就会超时。
先整体遍历长度之后,将长度保存,这样就不需要每次都遍历链表了。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
/**
* 先计算出链表的整体长度
* 然后得出中间值,将中间值作为根节点
* 中间值的前的链表截断作为左子树
* 中间值后的链表截断作为右子树
*/
int len = 0;
ListNode p = head;
while(head != null){
head = head.next;
len++;
}
return BST(p,len);
}
/**
* head 头结点
* len 链表长度
*/
private TreeNode BST(ListNode head, int len){
if(len <= 0){
return null;
}
if(len == 1){
return new TreeNode(head.val);
}
int mid = 0;
ListNode p = head;
ListNode nextHead = null;
//得到中间值
while(++mid < len/2){
p = p.next;
}
nextHead = p.next;//根节点
p.next = null;
TreeNode root = new TreeNode(nextHead.val);
//左右子树
root.left = BST(head,mid);
root.right = BST(nextHead.next,len-mid-1);
return root;
}
}