Because it requires the height balanced BST, just cut the list into half and half and go recursion.
Solution:
# T:O(n) S:O(lgn) class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): length = len(num) if length == 0: return None if length == 1: return TreeNode(num[0]) root = TreeNode(num[length / 2]) root.left = self.sortedArrayToBST(num[:length/2]) root.right = self.sortedArrayToBST(num[length/2 + 1:]) return rootRun Time: 96 ms
No comments:
Post a Comment