版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/86489605
给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例
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;
}
}