-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path109. Convert Sorted List to Binary Search Tree.py
60 lines (60 loc) · 1.77 KB
/
109. Convert Sorted List to Binary Search Tree.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
#this part is done by storing linkedlist into an array and then created the tree
# a=[]
# temp=head
# while temp:
# a.append(temp.val)
# temp=temp.next
#
# root=self.creator(a)
# return root
#
#def creator(self,a):
# if not a:
# return
# mid=len(a)//2
# root=TreeNode(a[mid])
#
# root.left=self.creator(a[:mid])
# root.right=self.creator(a[mid+1:])
# return root
#using linked list only
root=self.creator(head)
return root
def creator(self,head):
if head is None:
return
if head.next is None:
return TreeNode(head.val)
temp=head
slow=head
fast=head
prev=None
while fast and fast.next:
prev=slow
slow=slow.next
fast=fast.next.next
#print(prev)
if prev:
prev.next=None
#print(temp)
#print(slow)
root=TreeNode(slow.val)
root.left=self.creator(temp)
root.right=self.creator(slow.next)
#print('root',root.val)
return root