-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
O(n) time and O(1) space using recursion
- Loading branch information
Parth Shah
committed
Feb 22, 2021
1 parent
03ae86c
commit faccfa4
Showing
1 changed file
with
15 additions
and
0 deletions.
There are no files selected for viewing
15 changes: 15 additions & 0 deletions
15
...t Sorted Array to Binary Search Tree/108_1. Convert Sorted Array to Binary Search Tree.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |