Published:
Updated:


Solution

# Definition for a binary tree node.
from typing import List, Optional


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

        # ํ˜„์žฌ ์ค‘๊ฐ„ ๊ฐ’์ธ ๋…ธ๋“œ ์„ ์–ธ
        mid_node = len(nums) // 2
        # ๊ทธ ์ค‘๊ฐ„ ๊ฐ’์„ ๋ฃจํŠธ๋กœ ์„ ์–ธ (์ค‘๊ฐ„ ๊ฐ’์œผ๋กœ ํ•˜๋Š” ์ด์œ ๋Š” BST์—์„œ ์ค‘๊ฐ„ ๊ฐ’์ด ๊ฐ€์žฅ ๊ท ํ˜•์ ์ธ ๊ฐ’์ด๊ธฐ ๋•Œ๋ฌธ)
        root = TreeNode(nums[mid_node])

        # ์ค‘๊ฐ„ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ๋ฐฐ์—ด ์„ ์–ธ
        # ์™ผ์ชฝ ๋ฐฐ์—ด์€ ํ˜„์žฌ ๋…ธ๋“œ์˜ ์™ผ์ชฝ ์ž์‹ ๋…ธ๋“œ
        # ์˜ค๋ฅธ์ชฝ ๋ฐฐ์—ด์€ ํ˜„์žฌ ๋…ธ๋“œ์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹ ๋…ธ๋“œ
        nums_left = nums[:mid_node]
        nums_right = nums[mid_node + 1:]

        # ์™ผ์ชฝ ์ž์‹ ํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์ž์‹ ํŠธ๋ฆฌ๋ฅผ ๊ฐ๊ฐ ์žฌ๊ท€์ ์œผ๋กœ ์ƒ์„ฑ
        root.left = self.sortedArrayToBST(nums_left)
        root.right = self.sortedArrayToBST(nums_right)

        return root

Leave a comment