Skip to content

Commit

Permalink
O(n) time and O(1) space using recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
Parth Shah committed Feb 22, 2021
1 parent 03ae86c commit faccfa4
Showing 1 changed file with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
n = len(nums)
root = TreeNode(nums[n//2])
root.left = self.sortedArrayToBST(nums[:n//2])
root.right = self.sortedArrayToBST(nums[n//2+1:])
return root

0 comments on commit faccfa4

Please sign in to comment.