-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedListtoBinarySearchTree2.py
More file actions
48 lines (41 loc) · 1.08 KB
/
ConvertSortedListtoBinarySearchTree2.py
File metadata and controls
48 lines (41 loc) · 1.08 KB
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
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
numbers=[0,1,2,3,4,5]
dummyRoot = ListNode(0)
head = dummyRoot
for number in numbers:
head.next = ListNode(number)
head = head.next
head = dummyRoot.next
class Solution:
def sortedArrayToBST(self, head) -> TreeNode:
nums=[]
if head:
self.toList(head,nums)
return self.toTree(nums)
return None
def toList(self,head,nums):
while head:
nums.append(head.val)
head=head.next
def toTree(self,nums):
l=len(nums)
if l ==0:
return None
mid=int(l/2)
node=TreeNode(nums[mid])
if mid-1>=0:
node.left=self.toTree(nums[0:mid])
if mid+1<l:
node.right=self.toTree(nums[mid+1:])
return node
#nums=[-10,-3]
print (Solution().sortedArrayToBST(head))
#print (nums)