0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LeetCodeを1日1題解いてみる (day21)

Last updated at Posted at 2024-11-20

21日目に取り組んだ問題はこちら!

108. Convert Sorted Array to Binary Search Tree

問題文

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

僕の回答 (失敗作)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        mid = len(nums) // 2
        left_arr = nums[:mid]
        right_arr = nums[mid:]
        node = TreeNode(nums[mid])
        root = node     

回答例

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        if not nums:
            return None
        
        def buildBST(left: int, right: int) -> Optional[TreeNode]:
            if left > right:
                return None
            mid = (left + right) // 2
            node = TreeNode(nums[mid])

            node.left = buildBST(left, mid - 1)
            node.right = buildBST(mid + 1, right)

            return node
        
        return buildBST(0, len(nums) - 1)

コメント

こんな感じなのかな、というのは掴めるがそれを具体的にアルゴリズムとコードに落とし込むことが苦手です。

次の問題はこちら!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?