-
Notifications
You must be signed in to change notification settings - Fork 0
/
109.py
69 lines (61 loc) · 1.63 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
start = head
while start and start.next:
start = start.next
return self.cur(head, start)
def cur(self, head, end):
start = head
second_point = head
left_end = head
count = 0
if start is None:
return None
if start == end:
return TreeNode(start.val)
while start.next is not None and start != end:
start = start.next
if count % 2 == 0:
if count >= 1:
left_end = second_point
second_point = second_point.next
count += 1
root = TreeNode(second_point.val)
if second_point!=left_end:
root.left = self.cur(head, left_end)
if second_point!=end:
root.right = self.cur(second_point.next, end)
return root
a = ListNode(-10)
b = ListNode(-3)
c = ListNode(0)
d = ListNode(5)
e = ListNode(9)
a.next = b
b.next = c
c.next = d
d.next = e
solu = Solution()
res = solu.sortedListToBST(a)
def printtree(res):
print res.val
if res.left:
print res.val,'=>left',printtree(res.left)
if res.right:
print res.val,'=>right',printtree(res.right)
printtree(res)