Leetcode - 108. Convert Sorted Array to Binary Search Tree
Coding Test

Leetcode - 108. Convert Sorted Array to Binary Search Tree

일시불

문제

Loading...
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.

풀이

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if len(nums) == 0:
            return None
        if len(nums) == 1:
            return TreeNode(nums[0])

        centroid = len(nums) // 2
        return TreeNode(
            numbers[centroid],
            create_bst(nums[:centroid]),
            create_bst(nums[centroid + 1 :]),
        )

사실은 길이가 1일때는 Base case가 아니다. 1//2=0이기 때문이다.

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        if len(nums) == 0:
            return None

        centroid = len(nums) // 2
        return TreeNode(
            numbers[centroid],
            create_bst(nums[:centroid]),
            create_bst(nums[centroid + 1 :]),
        )