Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
第一种方法,把linkedlist转化成arraylist,使用二分法构建BST。代码如下:
/**
* 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; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
List<Integer> list = new ArrayList<Integer>();
while (head != null) {
list.add(head.val);
head = head.next;
}
TreeNode root = helper(list, 0, list.size() - 1);
return root;
}
private TreeNode helper(List<Integer> list, int i, int j) {
if (i > j) {
return null;
}
int mid = i + (j - i) / 2;
TreeNode root = new TreeNode(list.get(mid));
root.left = helper(list, i, mid - 1);
root.right = helper(list, mid + 1, j);
return root;
}
}
第二种方法,使用双指针法在linkedlist遍历,取slow.val作为root.val。代码如下:
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;
}
}