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

+ Recent posts