Question
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
*Difficulty: Hard, Frequency: Low
Bottom-up Recursion Solution
O(n) runtime, O(log n) stack space – Bottom-up recursion
/**
* 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 {
private ListNode list;
public TreeNode sortedListToBST(ListNode head) {
int len = 0;
ListNode p = head;
while(p != null){
p = p.next;
len++;
}
list = head;
return getSubtree(0, len-1);
}
public TreeNode getSubtree(int start, int end){
if(start > end) return null; //reached the leaf's child
int mid = (start + end) / 2;
//kind of like the in-order traverse
TreeNode left = getSubtree(start, mid-1);
TreeNode node = new TreeNode(list.val);
node.left = left;
list = list.next;//very crucial steps!!
node.right = getSubtree(mid+1, end);
return node;
}
}