题意:
给出一个排好序的单链表,将它转化为平衡的二叉搜索树。
初步分析:
基于上一篇的考虑,我们现在来考虑递归,那么问题来了,我们对于一个数组区间的描述,需要数组本身,起点角标,终点角标。但是链表不是这样的,
我们来思考!链表需要头结点(即表示了链表)和长度或者头结点和尾节点能充分完全的表示出一段链表。长度我们首先要知道链表的长度,所以需要先遍历,我们暂且不考虑,暂时用头结点和尾节点(不容易出现越界等等错误)
那么,问题又来了,我们怎么取得中间的结点呢,我们可以采用动态的two-pointer的方法。
/**
* 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) {
return sortedListToBST(head, null);
}
public TreeNode sortedListToBST(ListNode head, ListNode end)
{
if (head==end)
return null;
ListNode slow=head, fast=head; //slow是middle结点
while (fast.next!=end && fast.next.next!=end) //快慢指针的方法!
{
slow=slow.next;
fast=fast.next.next;
}
TreeNode node = new TreeNode(slow.val);
node.left=sortedListToBST(head, slow);
node.right=sortedListToBST(slow.next, end);
return node;
}
}