-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path109. Convert Sorted List to Binary Search Tree.java
48 lines (48 loc) · 1.44 KB
/
109. Convert Sorted List to Binary Search Tree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 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) {
if(head == null) return null;
return _sortedListToBST(head, null);
}
private TreeNode _sortedListToBST(ListNode head, ListNode tailNode) {
if (head == tailNode) return null;
// find middle of the linekdList
// 2 pointer approch
ListNode fast = head;
ListNode slow = head;
while (fast != tailNode && fast.next != tailNode){
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = _sortedListToBST(head, slow);
root.right = _sortedListToBST(slow.next, tailNode);
return root;
}
}