Created
October 27, 2018 05:26
-
-
Save hsaputra/a591b7347043d3ea1a51278600d367dc to your computer and use it in GitHub Desktop.
Leetcode 109 Convert Sorted List to Binary Search Tree
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; } | |
* } | |
*/ | |
class Solution { | |
public TreeNode sortedListToBST(ListNode head) { | |
if (head == null) { | |
return null; | |
} | |
if (head.next == null) { | |
// only one so return quick | |
return new TreeNode(head.val); | |
} | |
return recursiveFromMiddle(head, null); | |
} | |
private TreeNode recursiveFromMiddle(ListNode start, ListNode end) { | |
// Stopping condition | |
if (start == end) { | |
return null; | |
} | |
// get from middle and push it down | |
ListNode med = start; | |
ListNode fast = start.next; | |
// since it is sorted we knew it left of middle is smaller and right is bigger | |
TreeNode parentNew = null; | |
while (fast != end && fast.next != end) { | |
med = med.next; | |
fast = fast.next.next; | |
} | |
TreeNode root = new TreeNode(med.val); | |
root.left = recursiveFromMiddle(start, med); | |
root.right = recursiveFromMiddle(med.next, end); | |
return root; | |
} | |
} |
Author
hsaputra
commented
Oct 27, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment