https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree
주어진 리스트는 정렬되어있기 때문에, 정중앙값이 무조건 root 가 된다.
따라서 리스트의 중앙값을 찾아서 TreeNode의 val 로 설정하고,
중앙값의 왼쪽 리스트를 TreeNode 의 left 로 설정하고,
중앙값의 오른쪽 리스트를 TreeNode 의 right 로 설정하면 된다.
리스트가 None 이거나, 리스트의 길이가 1개 이하일때는, 그 자체로 완성된 BST 이므로 리스트를 TreeNode 로 그대로 반환한다.
python 은 간단하게 리스트를 자르는 방법을 제공하므로 이 방법을 이용하면 직관적인 코드를 작성할 수 있다.
리스트를 자르는 행위는 O(n) 시간을 소모하므로 효율적이지 못하다.
따라서 리스트를 실제로 자르지 않고, 인덱스를 사용하여 논리적으로 잘라 판단한다.
# 리스트를 실제로 잘라서 사용
class Solution:
def func(self, nums: List[int], mid: int) -> Optional[TreeNode]:
if(not nums or len(nums)==0): return None
if(len(nums)==1): return TreeNode(nums[0])
tree = TreeNode(nums[mid])
left = nums[0:mid]
right = nums[mid+1:len(nums)]
tree.left = self.func(left, len(left)//2)
tree.right = self.func(right, len(right)//2)
return tree
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
return self.func(nums, len(nums)//2)
# 인덱스를 이용하여 리스트를 구분
class Solution:
def func(self, nums: List[int], li: int, ri: int) -> Optional[TreeNode]:
if(not nums or li>=ri): return None
if(li==ri+1): return TreeNode(nums[0])
mid = (li+ri)//2
tree = TreeNode(nums[mid])
tree.left = self.func(nums, li, mid)
tree.right = self.func(nums, mid+1, ri)
return tree
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
return self.func(nums, 0, len(nums))
< English (feedback by ChatGPT) >
The given list is already sorted, so the middle value in the list becomes a root without a reason.
(The given list is already sorted, so the middle value will always be the root of the BST.)
So, we can find the middle value in the list and set it as a TreeNode's 'val',
(We find the middle value and assign it as the val of a TreeNode.)
set the left part of the list from the middle value as a TreeNode's 'left',
set the right part of the list from the middle value as a TreeNode's 'right'.
(Then we recursively assign the left part of the list (before the middle) as the left child,
and the right part (after the middle) as the right child.)
If the list is None or the length of the list is less than 1, it means the list is already complete BST,
so just we can retrun the list itself as a TreeNode.
(If the list is None or its length is 1 or less, it is already a complete BST,
so we can directly return it as a TreeNode.)
Python supports an easy way to chop a list, so we can use the way to write some intuitive codes.
(Python provides a convenient way to slice lists, which allows us to write intuitive code.)
Chopping a list needs O(n) time complexity, and it is not efficient.
(However, slicing a list takes O(n) time, which is not efficient.)
So we can use indexes to seperate the list rather than chopping.
(To improve performance, we can avoid slicing and instead use index boundaries to simulate the splits logically.)
'Coding Interview' 카테고리의 다른 글
[leetcode] 111. Minimum Depth of Binary Tree (0) | 2025.05.07 |
---|---|
[leetcode] 110. Balanced Binary Tree (0) | 2025.05.06 |
[leetcode] 100. Same Tree (0) | 2025.05.05 |
[leetcode] 70. Climbing Stairs (0) | 2025.05.05 |
[leetcode] 21. Merge Two Sorted Lists (0) | 2025.05.03 |