给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例
2
1->2->3 => / \
1 3
解题思路:
明显的思路是寻找链表的中间节点,然后得到其根节点,然后分割链表为左右两部分,继续递归的寻找每部分链表的中间节点作为根节点的左右子树。
一个问题在于不能直接寻找中间节点,因为这样就无法去除掉中间节点分割左半部分的链表,所以需要利用快慢指针的变形(对fast节点初始向后移一位即可)寻找中间节点的前一个节点,从而能正确分割链表。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
public TreeNode sortedListToBST(ListNode head) {
// write your code here
if(head == null)
return null;
if(head.next == null)
return new TreeNode(head.val);
//寻找中间节点,然后分割链表
ListNode slow = head; //指向中点的前一个节点
ListNode fast = head.next;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode midNode = slow.next;//中间节点
TreeNode treeNode = new TreeNode(midNode.val);
slow.next = null;//分割链表
//分治
treeNode.left = sortedListToBST(head);
treeNode.right = sortedListToBST(midNode.next);
return treeNode;
}
}
二刷:
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
public TreeNode sortedListToBST(ListNode head) {
// write your code here
if(head == null)
return null;
ListNode slowPre = null;//指向slow的前一个元素
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slowPre = slow;
slow = slow.next;
fast = fast.next.next;
}
if(slowPre != null)
slowPre.next = null;
ListNode mid = slow;
ListNode head1 = null;//为了防止head == mid时出现无限递归
if(head != mid)
head1 = head;
ListNode head2 = mid.next;
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(head1);
root.right = sortedListToBST(head2);
return root;
}
}