-
Notifications
You must be signed in to change notification settings - Fork 1
/
LC109_ConvertSortedListtoBinarySearchTree.py
52 lines (32 loc) · 1.17 KB
/
LC109_ConvertSortedListtoBinarySearchTree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
arr = []
temp = head
while temp:
arr.append(temp.val)
temp = temp.next
prev = ListNode('inf')
def helper(left, right):
nonlocal arr
if left > right:
return None
mid = (left+right)//2
node = TreeNode(arr[mid])
if left == right:
return node
node.left = helper(left, mid-1)
node.right = helper(mid+1, right)
return node
prev.next = helper(0, len(arr)-1)
return prev.next