Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d062599

Browse files
109. Convert Sorted List to Binary Search Tree (java)
1 parent 4ab7a26 commit d062599

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public TreeNode sortedListToBST(ListNode head) {
3+
if(head==null) return null;
4+
if(head.next==null) return new TreeNode(head.val);
5+
ListNode slow = head;
6+
ListNode fast = head;
7+
ListNode prev = null;
8+
while(fast!=null && fast.next!=null){
9+
prev = slow;
10+
slow=slow.next;
11+
fast=fast.next.next;
12+
}
13+
TreeNode root = new TreeNode(Objects.requireNonNull(prev).next.val);
14+
prev.next = null;
15+
root.left = sortedListToBST(head);
16+
root.right = sortedListToBST(slow.next);
17+
return root;
18+
}
19+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /