给定一个单链表的头节点 head ,其中的元素 按升序排序 ,将其转换为高度平衡的二叉搜索树。
中等难度。首先通过快慢指针找出链表的中间节点,该节点作为当前树的根节点,然后当前链表节点的左边部分链表和右边部分链表进行递归的调用,得到的结果作为当前树的根节点的左右子树节点。
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return new TreeNode(head.val);
}
//快慢指针查找链表中间节点
ListNode fast = head, slow = head, pre = null;
while (fast != null && fast.next != null) {
fast = fast.next.next;
pre = slow;
slow = slow.next;
}
//断开左边链表的连接
pre.next = null;
//slow作为当前节点
TreeNode root = new TreeNode(slow.val);
//前驱作为左链表的尾节点,递归构造左子节点
root.left = sortedListToBST(head);
//后继作为右链表的头节点,递归构造右子节点
root.right = sortedListToBST(slow.next);
return root;
}