-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path109.py
52 lines (41 loc) · 1.07 KB
/
109.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, 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 func(self, head):
if head is None:
return None
if head.next is None:
return TreeNode(head.val)
mid = None
slow = head
fast = head
prev = None
while fast is not None and fast.next is not None:
prev = slow
slow = slow.next
fast = fast.next.next
mid = slow
prev.next = None
t = TreeNode(mid.val)
t.left = self.func(head)
t.right = self.func(mid.next)
return t
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
if head is None:
return None
if head.next is None:
return TreeNode(head.val)
return self.func(head)