59 lines
1.5 KiB
Java
59 lines
1.5 KiB
Java
/*
|
|
* @lc app=leetcode id=109 lang=java
|
|
*
|
|
* [109] Convert Sorted List to Binary Search Tree
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* Definition for singly-linked list.
|
|
* public class ListNode {
|
|
* int val;
|
|
* ListNode next;
|
|
* ListNode() {}
|
|
* ListNode(int val) { this.val = val; }
|
|
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
|
|
* }
|
|
*/
|
|
/**
|
|
* Definition for a binary tree node.
|
|
* public class TreeNode {
|
|
* int val;
|
|
* TreeNode left;
|
|
* TreeNode right;
|
|
* TreeNode() {}
|
|
* TreeNode(int val) { this.val = val; }
|
|
* TreeNode(int val, TreeNode left, TreeNode right) {
|
|
* this.val = val;
|
|
* this.left = left;
|
|
* this.right = right;
|
|
* }
|
|
* }
|
|
*/
|
|
class Solution {
|
|
public TreeNode sortedListToBST(ListNode head) {
|
|
return buildTree(head);
|
|
}
|
|
|
|
private TreeNode buildTree(ListNode head) {
|
|
if(head == null || head.next == null) {
|
|
return head == null ? null : new TreeNode(head.val, null, null);
|
|
}
|
|
ListNode dummy = new ListNode(0);
|
|
dummy.next = head;
|
|
ListNode slow = dummy, fast = dummy, prev = dummy;
|
|
while(fast != null && fast.next != null) {
|
|
fast = fast.next.next;
|
|
prev = slow;
|
|
slow = slow.next;
|
|
}
|
|
prev.next = null;
|
|
TreeNode tree = new TreeNode(slow.val, null, null);
|
|
tree.left = buildTree(dummy.next);
|
|
tree.right = buildTree(slow.next);
|
|
return tree;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|