题目:将一个排序后链表转成一个平衡二叉查找树
难度:Medium
思路:这题的思路跟将有序数组转成平衡二叉查找树一样,查找一个链表的中间元素需要定义两个指针,fast指针每次移动两步,slow指针每次移动一步,fast指针移动到链表尾部时,slow指向的节点为中间节点
- 代码:
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null){
return null;
}
return recursion(head, null);
}
public TreeNode recursion(ListNode head, ListNode tail){
if(head == tail){
return null;
}
ListNode slow = head;
ListNode fast = head;
while(fast != tail && fast.next != tail){
slow = slow.next;
fast = fast.next.next;
}
TreeNode node = new TreeNode(slow.val);
node.left = recursion(head, slow);
node.right = recursion(slow.next, tail);
return node;
}
}