Convert Sorted List to Binary Search Tree (Leetcode 109)
Problem Link: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
class Solution:
def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
if(head is None):
return None
elif(head.next is None):
return TreeNode(head.val)
prev=ListNode(-1)
prev.next=head
s=head
f=head
while(f is not None and f.next is not None):
s=s.next
prev=prev.next
f=f.next.next
rootnodeval=s.val
r=s.next
s.next=None
prev.next=None
l=head
temp=l
rootnode=TreeNode(rootnodeval)
l=self.sortedListToBST(l)
r=self.sortedListToBST(r)
rootnode.left=l
rootnode.right=r
return rootnode
PreviousFind the corresponding node of a binary tree in the clone of that tree (Leetcode 1379)NextLowest Common Ancestor of a Binary Tree (Leetcode 236)
Last updated