Created
August 23, 2013 06:52
-
-
Save charlespunk/6316271 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. |
This file contains hidden or 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
/** | |
* 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