Scribbling

LeetCode: 109. Convert Sorted List to Binary Search Tree 본문

Computer Science/Coding Test

LeetCode: 109. Convert Sorted List to Binary Search Tree

focalpoint 2021. 10. 27. 19:44
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# 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 sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
        if not head:
            return None
        values = []
        cur = head
        while cur != None:
            values.append(cur.val)
            cur = cur.next
        return self.tree_builder(values)
            
    def tree_builder(self, values):
        if not values:
            return None
        
        if len(values) == 1:
            return TreeNode(val=values[0])
        
        mid_idx = len(values) // 2
        mid_value = values[mid_idx]
        head = TreeNode(val=mid_value)
        
        head.left = self.tree_builder(values[:mid_idx])
        head.right = self.tree_builder(values[mid_idx+1:])
        
        return head

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 115. Distinct Subsequences  (0) 2021.10.27
LeetCode: 113. Path Sum II  (0) 2021.10.27
프로그래머스: 도둑질  (0) 2021.10.26
프로그래머스: 등굣길  (0) 2021.10.26
프로그래머스: 정수 삼각형  (0) 2021.10.26