Skip to content

Commit a3cfa6d

Browse files
committed
refine
1 parent 2e4c572 commit a3cfa6d

File tree

1 file changed

+24
-24
lines changed

1 file changed

+24
-24
lines changed
Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11

2-
32
/**
4-
* Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
3+
* Given a singly linked list where elements are sorted in ascending order,
4+
* convert it to a height balanced BST.
55
*/
66

77
public class ConvertSortedListtoBinarySearchTree {
88
public TreeNode sortedListToBST(ListNode head) {
9-
return sortedListToBST(head, null);
10-
}
11-
12-
private TreeNode sortedListToBST(ListNode start, ListNode end) {
13-
if (start == end) {
14-
return null;
15-
} else if (start.next == end) {
16-
return new TreeNode(start.val);
17-
} else {
18-
ListNode fast = start, slow = start;
19-
while (fast.next != end && fast.next.next != end) {
20-
fast = fast.next.next;
21-
slow = slow.next;
22-
}
23-
TreeNode left = sortedListToBST(start, slow);
24-
TreeNode right = sortedListToBST(slow.next, end);
25-
TreeNode root = new TreeNode(slow.val);
26-
root.left = left;
27-
root.right = right;
28-
return root;
29-
}
30-
}
9+
return sortedListToBST(head, null);
10+
}
11+
12+
private TreeNode sortedListToBST(ListNode start, ListNode end) {
13+
if (start == end) {
14+
return null;
15+
} else if (start.next == end) {
16+
return new TreeNode(start.val);
17+
} else {
18+
ListNode fast = start, slow = start;
19+
while (fast.next != end && fast.next.next != end) {
20+
fast = fast.next.next;
21+
slow = slow.next;
22+
}
23+
TreeNode left = sortedListToBST(start, slow);
24+
TreeNode right = sortedListToBST(slow.next, end);
25+
TreeNode root = new TreeNode(slow.val);
26+
root.left = left;
27+
root.right = right;
28+
return root;
29+
}
30+
}
3131
}

0 commit comments

Comments
 (0)