给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例
2
1->2->3 => / \
1 3
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
public static TreeNode sortedListToBST(ListNode head){
TreeNode root=null;
if(head==null){
return root;
}
ArrayList<Integer> list=new ArrayList<Integer>();
while(head!=null){
list.add(head.val);
head=head.next;
}
TreeNode result=fun(root, list, 0, list.size()-1);
return result;
}
private static TreeNode fun(TreeNode root, ArrayList<Integer> list, int start, int end){
if(start>end){
return null;
}else{
int mid=(start+end)/2;
root=new TreeNode(list.get(mid));
root.left=fun(root, list, start, mid-1);
root.right=fun(root, list, mid+1, end);
return root;
}
}
}