Leetcode :: Convert Sorted Array to Binary search Tree

wisepineยท2021๋…„ 5์›” 25์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
100/121
post-thumbnail

Problems

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

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.


Guess

  • ์žฌ๊ท€๋กœ ๋‘๊ฐœ์˜ subtree๋ฅผ ๊ตฌ์„ฑ
  • ๋ฐ˜๋ณต์ ์œผ๋กœ root๋ฅผ ํ• ๋‹น (๊ฐ€์šด๋ฐ๊ฐ’)

Solution

# 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]) -> TreeNode:
        if not nums:
            return None
        
        mid = len(nums) // 2
        
        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST(nums[:mid])
        root.right = self.sortedArrayToBST(nums[mid+1:])
        
        return root
profile
๋ฐฐ์šด๊ฑฐ ์•„์นด์ด๋น™ํ•˜๋Š” ๊ณณ

0๊ฐœ์˜ ๋Œ“๊ธ€