package Depth_first_Search;
public class SortedListToBST_109 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode sortedListToBST(ListNode head) {
if(head==null) {
return null;
}
ListNode mid=findMiddleNode(head);
TreeNode node=new TreeNode(mid.val);
if(head==mid) {
return node;
}
node.left=sortedListToBST(head);
node.right=sortedListToBST(mid.next);
return node;
}
ListNode findMiddleNode(ListNode head){
ListNode prePtr=null;
ListNode slowPtr=head;
ListNode fastPtr=head;
while(fastPtr!=null&&fastPtr.next!=null) {
prePtr=slowPtr;
slowPtr=slowPtr.next;
fastPtr=fastPtr.next.next;
}
if(prePtr!=null) {
prePtr.next=null;
}
return slowPtr;
}
}