Skip to content

Commit f232538

Browse files
authored
Create 108-convert_sorted_arr_into_bst.py
1 parent 965e1e9 commit f232538

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

108-convert_sorted_arr_into_bst.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""
2+
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/
3+
4+
Strat: Look for the middle elem, then recurse on left and right.
5+
6+
Stats:
7+
Runtime: 72 ms, faster than 24.04% of Python online submissions for Convert Sorted Array to Binary Search Tree.
8+
Memory Usage: 17 MB, less than 65.96% of Python online submissions for Convert Sorted Array to Binary Search Tree.
9+
10+
"""
11+
# Definition for a binary tree node.
12+
# class TreeNode(object):
13+
# def __init__(self, val=0, left=None, right=None):
14+
# self.val = val
15+
# self.left = left
16+
# self.right = right
17+
class Solution(object):
18+
def sortedArrayToBST(self, nums):
19+
"""
20+
:type nums: List[int]
21+
:rtype: TreeNode
22+
"""
23+
if nums:
24+
mid = len(nums) // 2
25+
return self.helper(nums[:mid], nums[mid], nums[mid + 1:])
26+
else:
27+
return None
28+
29+
def helper(self, left, mid, right):
30+
# print(left, mid, right)
31+
parent = TreeNode(mid)
32+
33+
#work out left node
34+
if left:
35+
mid = len(left) // 2
36+
parent.left = self.helper(left[:mid], left[mid], left[mid + 1:])
37+
38+
#work out right node
39+
if right:
40+
mid = len(right) // 2
41+
parent.right = self.helper(right[:mid], right[mid], right[mid + 1:])
42+
43+
return parent
44+

0 commit comments

Comments
 (0)