问题
给定一个升序排列的有序单链表,将其转换为一棵平衡的二叉搜索树。
思路
先找到链表中间节点作为根节点,然后递归左右两半部分。可以使用快慢指针找到中间节点。
代码
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
if(head.next == null){
return new TreeNode(head.val);
}
//用快慢指针找到中间节点
ListNode slow = head;
ListNode fast = head;
ListNode preSlow = null;
while(fast.next != null && fast.next.next != null){
preSlow = slow;
slow = slow.next;
fast = fast.next.next;
}
//分别递归左右两部分
TreeNode mid = new TreeNode(slow.val);
if(preSlow != null){
preSlow.next = null;
mid.left = sortedListToBST(head);
}
if(slow.next != null){
mid.right = sortedListToBST(slow.next);
}
return mid;
}