forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0109.py
More file actions
42 lines (33 loc) · 957 Bytes
/
0109.py
File metadata and controls
42 lines (33 loc) · 957 Bytes
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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
len = self.getLength(head)
def helper(l, r):
nonlocal head
if l > r:
return None
mid = (l + r) >> 1
left = helper(l, mid - 1)
node = TreeNode(head.val)
head = head.next
node.left = left
node.right = helper(mid + 1, r)
return node
return helper(0, len - 1)
def getLength(self, head: ListNode) -> int:
curr = head
len = 0
while curr:
len += 1
curr = curr.next
return len