- Published on
Leetcode - 108. Convert Sorted Array to Binary Search Tree
- Authors
- Name
- Indo Yoon
Table of Contents
문제
[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.
LeetCode
](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/)
풀이
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 :]),
)