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.
Top-down approach will take n^2 time, cause each time you need to find the root in the linked list, then recursively construct the two parts.
Bottom-Up approach, you need to keep track of from where to build the sub tree and for how many nodes this sub tree has. so the current is used for this purpose.
/**
* 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 {
ListNode cur = null;
public TreeNode sortedListToBST(ListNode head) {
int size = getLen(head);
cur = head;
return getBST(size);
}
private TreeNode getBST(int size){
if(size <=0) return null;
TreeNode left = getBST(size/2);
TreeNode root = new TreeNode(cur.val);
cur = cur.next;
TreeNode right = getBST(size -1 - size/2);
root.left = left;
root.right = right;
return root;
}
private int getLen(ListNode head){
int l = 0;
while(head != null){
head = head.next;
l++;
}
return l;
}
}