Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 6, 2021 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/0127fa12396b72fab7e99db3fcd1160f to your computer and use it in GitHub Desktop.
Save vrat28/0127fa12396b72fab7e99db3fcd1160f to your computer and use it in GitHub Desktop.
Convert Sorted List to BST
class Solution {
ListNode curr;
public TreeNode sortedListToBST(ListNode head) {
int count = 0;
curr = head;
while (curr != null) {
curr = curr.next;
count++;
}
curr = head;
return treeify(1, count);
}
private TreeNode treeify(int i, int j) {
if (j < i) return null;
int mid = i + j >> 1;
TreeNode node = new TreeNode();
node.left = treeify(i, mid - 1);
node.val = curr.val;
curr = curr.next;
node.right = treeify(mid + 1, j);
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment