-
Notifications
You must be signed in to change notification settings - Fork 481
/
0109.py
36 lines (31 loc) · 890 Bytes
/
0109.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
# 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):
"""
:type head: ListNode
:rtype: TreeNode
"""
if not head:
return
if not head.next:
return TreeNode(head.val)
slow, fast = head, head.next.next # fast
while fast and fast.next:
slow = slow.next
fast = fast.next.next
tmp = slow.next
slow.next = None
res = TreeNode(tmp.val)
res.left = self.sortedListToBST(head)
res.right = self.sortedListToBST(tmp.next)
return res