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
77public 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