给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9],
一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
思路:将给定的有序链表转换为二叉搜索树的第一步是确定根节点。由于我们需要构造出平衡的二叉树,因此比较直观的想法是让根节点左子树中的节点个数与右子树中的节点个数尽可能接近。这样一来,左右子树的高度也会非常接近,可以达到高度差绝对值不超过 1 的题目要求。
具体操作:
-
快慢指针找出中间节点
mid
,将中间节点作为树的根节点。 -
断开
mid
前后指针,至于前指针,我们要维护一个slow
的前节点。所以还要创建一个虚节点。 -
找出中节点
mid
后,对于左边和右边进行相同的操作。
Java实现如下:
/**
* 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;
ListNode slow = head;
ListNode fast = head;
ListNode mid = null;
ListNode head2 = null;
ListNode vHead1 = new ListNode(-1);
vHead1.next = head;
ListNode vHead2 = new ListNode(-2);
ListNode pre = vHead1;
while(fast.next != null && fast.next.next != null){
pre = pre.next;
slow = slow.next;
fast = fast.next.next;
}
mid = slow;
pre.next = null;
vHead2 = mid.next;
mid.next = null;
TreeNode treeHead = new TreeNode(mid.val);
if(vHead1.next != null) treeHead.left = sortedListToBST(vHead1.next);
if(vHead2.next != null) treeHead.right = sortedListToBST(vHead2.next);
return treeHead;
}
}