Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
思路:链表已有序,所以可以利用其特点,找到中间节点作为二叉搜索树的根节点,然后递归构建树。因为二叉搜索树的特点就是中序遍历是递增数列,每个子树的根节点为中值。
/**
* 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 recursive(ListNode head){
if(head == null) return null;
if(head.next == null) return new TreeNode(head.val);
ListNode fast = head;
ListNode slow = head;
ListNode pre = null;
while(slow.next != null && fast.next != null &&fast.next.next != null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
ListNode mid = (fast.next == null)? slow:slow.next;
pre = (fast.next == null)? pre:slow;
ListNode post = (mid==null)?null:mid.next;
pre.next = null;
if(mid != null) mid.next = null;
TreeNode root = new TreeNode(mid.val);
root.left = recursive(head);
root.right = recursive(post);
return root;
}
public TreeNode sortedListToBST(ListNode head) {
return recursive(head);
}
}
更简洁的写法:
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
return toBST(head,null);
}
public TreeNode toBST(ListNode head, ListNode tail){
ListNode slow = head;
ListNode fast = head;
if(head==tail) return null;
while(fast!=tail&&fast.next!=tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode thead = new TreeNode(slow.val);
thead.left = toBST(head,slow);
thead.right = toBST(slow.next,tail);
return thead;
}
}