题目
题源
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d7bd3fbfdd6c3de65f536cb04507bdfe.png)
代码
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode preMid = MidNode(head);
ListNode MidNode = preMid.next;
preMid.next = null;
TreeNode tn = new TreeNode(MidNode.val);
tn.left = sortedListToBST(head);
tn.right = sortedListToBST(MidNode.next);
return tn;
}
private ListNode MidNode(ListNode head) {
ListNode slowNode = head, fastNode = head.next;
ListNode pre = slowNode;
while (fastNode != null && fastNode.next != null) {
pre = slowNode;
slowNode = slowNode.next;
fastNode = fastNode.next.next;
}
return pre;
}
}