Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlespunk/6316271 to your computer and use it in GitHub Desktop.
Save charlespunk/6316271 to your computer and use it in GitHub Desktop.
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
int len = 0;
ListNode run = head;
while(run != null){
len++;
run = run.next;
}
ListNode[] ref = new ListNode[1];
ref[0] = head;
return bottomUp(ref, 1, len);
}
public TreeNode bottomUp(ListNode[] ref, int begin, int end){
if(begin > end) return null;
int mid = (begin + end) / 2;
TreeNode left = bottomUp(ref, begin, mid - 1);
TreeNode parent = new TreeNode(ref[0].val);
parent.left = left;
ref[0] = ref[0].next;
parent.right = bottomUp(ref, mid + 1, end);
return parent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment