Convert Sorted List to Binary Search Tree total accepted:32343 total submissions:117376 My submissions Question Solution
Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST
The question and convert array to binary search tree differ in that there is no random access with LinkedList so to find the midpoint you can only use fast and slow pointer to find.
This method is slower than turning the LinkedList directly into an array.
The code is as follows:
# Definition for a binary tree node# class treenode:# def __init__ (self, x): # self.val = x# self.left = No ne# self.right = none## Definition for singly-linked list.# class listnode:# def __init__ (self, x): # Self.val = x# self.next = Noneclass solution: # @param head, a list node # @return A tree node def conver T (self,head,tail): if Head==tail: return None if Head.next==tail: return TreeNode (head.val) mid=head Fast=head while fast!=tail and Fast.next!=tail: fast=fast.next.next mid= Mid.next Node=treenode (mid.val) Node.left=self.convert (head,mid) Node.right=self.convert ( Mid.next,tail) return node def sortedlisttobst (self, head): return Self.convert (Head,none)
109.Convert Sorted List to Binary Search Tree leetcode Python