- Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathConvertSortedListtoBinarySearchTree.java
More file actions
Latest commit
29 lines (28 loc) · 869 Bytes
/
Copy pathConvertSortedListtoBinarySearchTree.java
File metadata and controls
29 lines (28 loc) · 869 Bytes
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
/**
* Given a singly linked list where elements are sorted in ascending order, convert it to a height
* balanced BST.
*/
publicclassConvertSortedListtoBinarySearchTree {
publicTreeNodesortedListToBST(ListNodehead) {
returnsortedListToBST(head, null);
}
privateTreeNodesortedListToBST(ListNodestart, ListNodeend) {
if (start == end) {
returnnull;
} elseif (start.next == end) {
returnnewTreeNode(start.val);
} else {
ListNodefast = start, slow = start;
while (fast.next != end && fast.next.next != end) {
fast = fast.next.next;
slow = slow.next;
}
TreeNodeleft = sortedListToBST(start, slow);
TreeNoderight = sortedListToBST(slow.next, end);
TreeNoderoot = newTreeNode(slow.val);
root.left = left;
root.right = right;
returnroot;
}
}
}