[leetcode] 108. Convert Sorted Array to Binary Search Tree
2023. 3. 13. 15:31ㆍ노트/Algorithm : 알고리즘
Given an integer array nums where the elements are sorted in ascending order, convert it to a
binary search tree.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
Constraints:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums is sorted in a strictly increasing order.
# 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]) -> Optional[TreeNode]:
if not nums:
return None
mid = len(nums) // 2
node = TreeNode(nums[mid])
node.left = self.sortedArrayToBST(nums[:mid])
node.right = self.sortedArrayToBST(nums[mid+1:])
return node
'노트 > Algorithm : 알고리즘' 카테고리의 다른 글
[leetcode] 783. Minimum Distance Between BST Nodes (0) | 2023.03.21 |
---|---|
[leetcode] 110. Balanced Binary Tree (0) | 2023.03.13 |
[leetcode] 297. Serialize and Deserialize Binary Tree (0) | 2023.03.09 |
[leetcode] 617. Merge Two Binary Trees (0) | 2023.03.09 |
[leetcode] 226. Invert Binary Tree (0) | 2023.03.09 |