题目:Convert Sorted List to Binary Search Tree
难度:medium
问题描述:
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) {
ArrayList<Integer> list=new ArrayList<>();
while(head!=null){
list.add(head.val);
head=head.next;
}
return build(list,0,list.size()-1);
}
private TreeNode build(ArrayList<Integer> nums,int head,int tail){
if(head<tail){
int index=(head+tail+1)/2;
TreeNode root=new TreeNode(nums.get(index));
root.left=build(nums,head,index-1);
root.right=build(nums,index+1,tail);
return root;
}
else if(head>tail){
return null;
}else{
return new TreeNode(nums.get(head));
}
}
}