Question: https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

Question Name: Convert Sorted List to Binary Search Tree

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 | # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): ''' With a given array num, the root of the corresponding tree is always the middle one in the array. ''' treeSize = len(num) if treeSize == 0: return None else: root = TreeNode(num[treeSize//2]) root.left = self.sortedArrayToBST(num[:treeSize//2]) root.right = self.sortedArrayToBST(num[treeSize//2+1:]) return root # @param head, a list node # @return a tree node def sortedListToBST(self, head): ''' Firstly we convert the list into an array. Then we construct the BST with that array. ''' num = [] current = head while current != None: num.append(current.val) current = current.next return self.sortedArrayToBST(num) |

What’s the time complexity of this one? O(NlogN)? Definitely not O(N)…

If N is the number of nodes, why not O(N)?

Forgot to post mine