Skip to content

Commit adf5353

Browse files
committed
add a solution
1 parent 716e712 commit adf5353

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

Python/convert-sorted-array-to-binary-search-tree.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,24 @@ def perfect_tree_pivot(self, n):
4141
return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root
4242
# has more nodes and the right subtree is perfect.
4343

44-
44+
# Time: O(n)
45+
# Space: O(logn)
46+
class Solution2(object):
47+
def sortedArrayToBST(self, nums):
48+
"""
49+
:type nums: List[int]
50+
:rtype: TreeNode
51+
"""
52+
self.iterator = iter(nums)
53+
return self.helper(0, len(nums))
54+
55+
def helper(self, start, end):
56+
if start == end:
57+
return None
58+
59+
mid = (start + end) // 2
60+
left = self.helper(start, mid)
61+
current = TreeNode(next(self.iterator))
62+
current.left = left
63+
current.right = self.helper(mid+1, end)
64+
return current

0 commit comments

Comments
 (0)