Created
May 6, 2021 14:52
-
-
Save vrat28/0127fa12396b72fab7e99db3fcd1160f to your computer and use it in GitHub Desktop.
Convert Sorted List to BST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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