Created
May 25, 2017 18:20
-
-
Save BiruLyu/34c173cf0ada76a03c9cb9bda931f4b9 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 { | |
| public TreeNode sortedListToBST(ListNode head) { | |
| if(head == null) return null; | |
| return helper(head,null); | |
| } | |
| public TreeNode helper(ListNode head, ListNode tail){ | |
| ListNode fast = head; | |
| ListNode slow = head; | |
| if(head == tail) return null; | |
| //while(fast != tail && fast.next != tail){ | |
| //[1,2,3,4,5][1,2,3,4] | |
| //[3,2,5,1,null,4][3,2,4,1] | |
| while(fast.next != tail && fast.next.next != tail){ | |
| //[1,2,3,4,5][1,2,3,4] | |
| //[3,1,4,null,2,null,5][2,1,3,null,null,null,4] | |
| fast = fast.next.next; | |
| slow = slow.next; | |
| } | |
| TreeNode root = new TreeNode(slow.val); | |
| root.left = helper(head, slow); | |
| root.right = helper(slow.next, tail); | |
| return root; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment