给定一个单元链表,元素按升序排序,将其转换为高度平衡的BST。
对于这个问题,一个高度平衡的二叉树是指:其中每个节点的两个子树的深度相差不会超过 1 的二叉树。
示例:
给定的排序链表: [-10, -3, 0, 5, 9],
则一个可能的答案是:[0, -3, 9, -10, null, 5]
0
/
-3 9
/ /
-10 5
详见:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
Java实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null){
return null;
}
if(head!=null&&head.next==null){
return new TreeNode(head.val);
}
ListNode slow=head;
ListNode fast=head;
ListNode pre=null;
while(fast!=null&&fast.next!=null){
pre=slow;
slow=slow.next;
fast=fast.next.next;
}
TreeNode root=new TreeNode(slow.val);
if(pre!=null){
pre.next=null;
}
root.left=sortedListToBST(head);
root.right=sortedListToBST(slow.next);
return root;
}
}