109 Convert Sorted List to Binary Search Tree
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 ofeverynode 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
Solution)
By binary search from the list, we can make each left and right node based on the middle point.
space complexity (O(n))
/**
* 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 helper(ArrayList<ListNode> arr, int start, int end) {
if (start > end) return null;
if (start == end) {
return new TreeNode(arr.get(start).val);
}
int m = (start+end)/2;
TreeNode node = new TreeNode(arr.get(m).val);
node.left = helper(arr, start, m-1);
node.right = helper(arr, m+1, end);
return node;
}
public TreeNode sortedListToBST(ListNode head) {
ArrayList<ListNode> arr = new ArrayList<>();
ListNode cur = head;
while(cur != null) {
arr.add(cur);
cur = cur.next;
}
return helper(arr, 0, arr.size()-1);
}
}
Solution)
No additional space
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;
}
}