Convert Sorted List to Binary Search Tree java

时间:2023-03-09 04:12:44
Convert Sorted List to Binary Search Tree  java
 public TreeNode sortedListToBST(ListNode head) {
if(head==null) return new TreeNode(0);
ArrayList<TreeNode> arr=new ArrayList<TreeNode>();
while(head!=null)
{
arr.add(new TreeNode(head.val));
head=head.next;
} return BST(arr,0,arr.size()-1);
}
TreeNode BST(ArrayList<TreeNode> list,int start,int end)
{
if(start>=end)
{
return list.get(start);
}
else
{
int mid=start+(end-start)/2;
TreeNode root=list.get(mid);
root.left=BST(list,start,mid-1);
root.right=BST(list,mid+1,end); return root;
}
}