일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- Python
- 109. Convert Sorted List to Binary Search Tree
- 파이썬
- attribute
- Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- Class
- iterator
- data science
- Decorator
- concurrency
- 715. Range Module
- DWG
- Generator
- Python Code
- Protocol
- 프로그래머스
- 컴퓨터의 구조
- 운영체제
- 30. Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- 시바견
- kaggle
- 43. Multiply Strings
- 밴픽
- shiba
- Regular Expression
- LeetCode
- t1
- Python Implementation
Archives
- Today
- Total
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 |