Skip to content

Commit 504b2b4

Browse files
committed
Modified solution
1 parent 0de501f commit 504b2b4

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

convert_sorted_list_to_binary_search_tree/solution.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,22 @@ class Solution:
1717
def sortedListToBST(self, head):
1818
if head is None:
1919
return None
20-
pp = p = q = head
21-
while q is not None and q.next is not None:
22-
pp = p # pp is the previous node to p
23-
p = p.next
24-
q = q.next.next
25-
root = TreeNode(p.val)
26-
pp.next = None # Split the linked list
27-
if pp == p:
28-
left = None
2920
else:
21+
# Get the middle node
22+
slow = head
23+
fast = head
24+
prev = None # Previous node to slow (mid)
25+
while fast.next is not None and fast.next.next is not None:
26+
prev = slow
27+
fast = fast.next.next
28+
slow = slow.next
29+
if head == slow:
30+
head = None
31+
if prev is not None:
32+
prev.next = None
33+
root = TreeNode(slow.val)
3034
left = self.sortedListToBST(head)
31-
right = self.sortedListToBST(p.next)
32-
root.left = left
33-
root.right = right
34-
return root
35+
right = self.sortedListToBST(slow.next)
36+
root.left = left
37+
root.right = right
38+
return root

0 commit comments

Comments
 (0)