Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions invert-binary-tree/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'''
# 226. Invert Binary Tree

switch left and right child of each node

## TC: O(N)

visit each node once

## SC: O(h)

h is height of tree

- best case: O(logN), balanced tree
- worst case: O(N), skewed tree
'''
class Solution:
'''
DFS
'''
def invertTreeRecursive(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None

root.left, root.right = root.right, root.left

self.invertTree(root.left)
self.invertTree(root.right)

return root

'''
BFS
- 직관적인 stack 풀이
'''
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
stack = [root]

while stack:
node = stack.pop()
if not node:
continue

node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)

return root

'''
- 참고용 deque 풀이
'''
def invertTreeDeque(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
dq = deque([root])

while dq:
node = dq.popleft()
if not node:
continue

node.left, node.right = node.right, node.left
dq.append(node.left)
dq.append(node.right)

return root
45 changes: 45 additions & 0 deletions search-in-rotated-sorted-array/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
'''
# 33. Search in Rotated Sorted Array

binary search + condition check

이진 탐색 중, 왼쪽이 정렬되었을 때
- 타겟이 정렬된 왼쪽에 있는 경우, 왼쪽 탐색 (left부터 mid - 1 사이에서 타겟을 탐색)
- 타겟이 정렬된 왼쪽에 없을 경우, 오른쪽 탐색 (mid + 1부터 right 사이에서 타겟을 탐색)

이진 탐색 중, 오른쪽이 정렬되었을 때
- 타겟이 정렬된 오른쪽에 있는 경우, 오른쪽 탐색 (mid + 1부터 right 사이에서 타겟을 탐색)
- 타겟이 정렬된 오른쪽에 없을 경우, 왼쪽 탐색 (left부터 mid - 1 사이에서 타겟을 탐색)

## TC: O(log n)

binary search

## SC: O(1)

no extra space

'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1

while left <= right:
mid = left + (right - left) // 2

if nums[mid] == target:
return mid

if nums[left] <= nums[mid]: # is_left_sorted
if nums[left] <= target < nums[mid]: # is_target_left
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]: # is_target_right
left = mid + 1
else:
right = mid - 1

return -1