[LeetCode]109. 有序链表转换二叉搜索树(java实现)快慢指针找中点
1. 题目
2. 读题(需要重点注意的东西)
思路(快慢指针找中点):
链表与数组的区别: 不支持随机索引,因此在遍历中点的时候,需要额外的时间
因此有两条思路:
-
将链表的数据存在数组中,该题就变为了[LeetCode]108. 将有序数组转换为二叉搜索树(java实现)递归建立一颗二叉树,时间复杂度是O(n),空间复杂度为O(n)
-
不用数组存储来找中点,而是通过快慢指针来查找中点,时间复杂度O(nlogn),递归栈的深度为logn,空间复杂度O(logn)
此处以思路2作为本题的解题思路
链表找中点的操作: 快慢指针
让快指针fast和慢指针slow从头结点开始走,快指针fase每次走两步,慢指针slow每次走一步,当快指针走到终点的时候,此时慢指针的位置即为中间节点的位置。
3. 解法
---------------------------------------------------解法---------------------------------------------------:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return build(head,null);
}
private TreeNode build(ListNode start,ListNode end){
if(start == end) return null;
ListNode fast = start;
ListNode slow = start;
while(fast != end && fast.next != end){
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = build(start,slow);
root.right = build(slow.next,end);
return root;
}
}
可能存在的问题:
4. 可能有帮助的前置习题
5. 所用到的数据结构与算法思想
6. 总结
快慢指针找链表中点的