I am working on a Daily Coding Challenge to convert a sorted singly-linked list into a binary search tree.
We are given the head of the list; the definitions of
TreeNode are provided by the challenge.
Below is my code in Python 3.11. Code works fine and produces desired output.
Please can anyone review it in terms of readability and any optimization that can be made.
class Solution: def sortedListToBST(self, head: ListNode) -> TreeNode: def helper(beg, end): if beg > end: return None mid = (beg + end)//2 left = helper(beg, mid - 1) root = TreeNode(self.head.val) self.head = self.head.next root.left = left root.right = helper(mid + 1, end) return root self.head, copy, n = head, head, 0 while copy: copy = copy.next n += 1 return helper(0, n-1)