Given 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:
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
与108类似分别求出左右节点:
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) {
return null;
}
ListNode sizeNode = head;
int size = 0;
while(sizeNode!=null) {
sizeNode = sizeNode.next;
size ++;
}
return sortedListToBST(head,0,size-1);
}
public TreeNode sortedListToBST(ListNode head,int start,int end) {
if(start > end){
return null;
}
int mid = (end+start)/2;
int size = 0;
ListNode tmp = head;
while(size < mid) {
tmp = tmp.next;
size++;
}
TreeNode res = new TreeNode(tmp.val);
res.left = sortedListToBST(head,start,mid-1);
res.right = sortedListToBST(head,mid+1,end);
return res;
}
}
一看结果吓一跳。。。
优化方法:可以通过先把所有的数据存入一个list这样重新执行。