일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Regular Expression
- 715. Range Module
- concurrency
- Decorator
- 109. Convert Sorted List to Binary Search Tree
- kaggle
- Python Code
- attribute
- 프로그래머스
- Python
- Class
- 밴픽
- LeetCode
- 운영체제
- Python Implementation
- iterator
- 컴퓨터의 구조
- 파이썬
- 315. Count of Smaller Numbers After Self
- Protocol
- 43. Multiply Strings
- Generator
- DWG
- Convert Sorted List to Binary Search Tree
- shiba
- data science
- Substring with Concatenation of All Words
- t1
- 시바견
- 30. Substring with Concatenation of All Words
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 2022. 1. 26. 09:54O(N) Time complexity, O(1) Memory Solution using Recursion
# 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]:
return self.builder(head)
def builder(self, node):
if not node:
return None
if not node.next:
return TreeNode(val=node.val)
prvslow, slow, fast = None, node, node
while fast and fast.next:
prvslow = slow
slow = slow.next
fast = fast.next.next
prvslow.next = None
new_head = TreeNode(val=slow.val)
new_head.left = self.builder(node)
new_head.right = self.builder(slow.next)
return new_head
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 135. Candy (0) | 2022.02.03 |
---|---|
LeetCode: 366. Find Leaves of Binary Tree (0) | 2022.02.02 |
LeetCode: 302. Smallest Rectangle Enclosing Black Pixels (0) | 2022.01.25 |
LeetCode: 65. Valid Number (0) | 2022.01.20 |
LeetCode: 30. Substring with Concatenation of All Words (0) | 2022.01.17 |