Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b36b5a4

Browse files
New solution uploaded!
1 parent fbe17d8 commit b36b5a4

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'''
2+
Convert Sorted Array to Binary Search Tree
3+
4+
Input: nums = [-10,-3,0,5,9]
5+
Output: [0,-3,9,-10,null,5]
6+
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
7+
8+
'''
9+
10+
11+
12+
13+
14+
# Definition for a binary tree node.
15+
# class TreeNode:
16+
# def __init__(self, val=0, left=None, right=None):
17+
# self.val = val
18+
# self.left = left
19+
# self.right = right
20+
class Solution:
21+
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
22+
if not nums:
23+
return None
24+
25+
# find middle index
26+
mid = len(nums) // 2
27+
# make the middle element of root
28+
root = TreeNode(nums[mid])
29+
30+
# left subtree of root has all
31+
# values <arr[mid]
32+
root.left = self.sortedArrayToBST(nums[:mid])
33+
34+
# right subtree of root has all
35+
# values > arr[mid]
36+
root.right = self.sortedArrayToBST(nums[mid+1:])
37+
return root

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /