https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Convert Sorted Array to Binary Search Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
정렬된 배열을 이진 탐색 트리로 변환하는 문제이다.
재귀를 사용해 divide-conquer 방식으로 절반씩 분할해가면서 문제를 해결하였다.
소스 코드
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
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 938. Range Sum of BST [Python] (0) | 2022.09.03 |
---|---|
LeetCode - 1038. Binary Search Tree to Greater Sum Tree [Python] (0) | 2022.09.03 |
LeetCode - 310. Minimum Height Trees [Python] (0) | 2022.09.02 |
LeetCode - 110. Balanced Binary Tree [Python] (0) | 2022.09.02 |
LeetCode - 297. Serialize and Deserialize Binary Tree [Python] (0) | 2022.08.31 |