Skip to content

Commit 9a5e25f

Browse files
authored
Create 109. Convert Sorted List to Binary Search Tree.java
1 parent 6e90bc8 commit 9a5e25f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree
2+
3+
// NB: an extension of prob 108. Use slow/fast linked-list traversal to find mid element
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* public class ListNode {
8+
* int val;
9+
* ListNode next;
10+
* ListNode(int x) { val = x; }
11+
* }
12+
*/
13+
/**
14+
* Definition for a binary tree node.
15+
* public class TreeNode {
16+
* int val;
17+
* TreeNode left;
18+
* TreeNode right;
19+
* TreeNode(int x) { val = x; }
20+
* }
21+
*/
22+
public class Solution {
23+
public TreeNode helper(ListNode head, ListNode tail) {
24+
if (head == tail) return null;
25+
ListNode runner = head, runnerX2 = head;
26+
27+
while (runnerX2.next != tail && runnerX2.next.next != tail) {
28+
runner = runner.next;
29+
runnerX2 = runnerX2.next.next;
30+
}
31+
32+
TreeNode root = new TreeNode(runner.val);
33+
root.left = helper(head, runner);
34+
root.right = helper(runner.next, tail);
35+
36+
return root;
37+
}
38+
39+
public TreeNode sortedListToBST(ListNode head) {
40+
if (head == null) return null;
41+
return helper(head, null);
42+
}
43+
}

0 commit comments

Comments
 (0)