File tree Expand file tree Collapse file tree 1 file changed +17
-13
lines changed
convert_sorted_list_to_binary_search_tree Expand file tree Collapse file tree 1 file changed +17
-13
lines changed Original file line number Diff line number Diff line change @@ -17,18 +17,22 @@ class Solution:
17
17
def sortedListToBST (self , head ):
18
18
if head is None :
19
19
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
29
20
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 )
30
34
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
You can’t perform that action at this time.
0 commit comments