/**
* 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;
}
if(head.next == null){
return new TreeNode(head.val);
}
return helper(head, null);
}
private TreeNode helper(ListNode head, ListNode tail){
if(head == tail){
return null;
}
ListNode slow = head, fast = head;
while(fast.next != tail && fast.next.next != tail){
slow = slow.next;
fast = fast.next.next;
}
TreeNode node = new TreeNode(slow.val);
node.left = helper(head, slow);
node.right = helper(slow.next, tail);
return node;
}
}
[LeetCode] 109. Convert Sorted List to Binary Search Tree
最新推荐文章于 2017-03-31 11:39:00 发布