Created
February 8, 2017 03:40
-
-
Save Chen-tao/788808409a2d51b18939d8ad65aefcad 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
/** | |
* 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 { | |
static ListNode h; | |
public TreeNode sortedListToBST(ListNode head) { | |
if(head == null){ | |
return null; | |
} | |
h = head; | |
int len = getLength(head); | |
return sortedListToBST(0, len - 1); | |
} | |
// get list length | |
public int getLength(ListNode head) { | |
int len = 0; | |
ListNode p = head; | |
while (p != null) { | |
len++; | |
p = p.next; | |
} | |
return len; | |
} | |
// build tree bottom-up | |
public TreeNode sortedListToBST(int start, int end) { | |
if (start > end) | |
return null; | |
// mid | |
int mid = (start + end) / 2; | |
TreeNode left = sortedListToBST(start, mid - 1); | |
TreeNode root = new TreeNode(h.val); | |
h = h.next; | |
TreeNode right = sortedListToBST(mid + 1, end); | |
root.left = left; | |
root.right = right; | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment