diff --git a/maximum-depth-of-binary-tree/hyedall.py b/maximum-depth-of-binary-tree/hyedall.py new file mode 100644 index 0000000000..14d24dedcc --- /dev/null +++ b/maximum-depth-of-binary-tree/hyedall.py @@ -0,0 +1,31 @@ +""" +# https://leetcode.com/problems/maximum-depth-of-binary-tree/ + +시간 복잡도 : O(n) +공간 복잡도 : O(n) +""" + +# 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 maxDepth(self, root: TreeNode | None) -> int: + if not root: + return 0 + + answer = 0 + stack = [(root, 1)] + + while stack: + cur, depth = stack.pop() + answer = max(answer, depth) + + if cur.left: + stack.append((cur.left, depth+1)) + if cur.right: + stack.append((cur.right, depth+1)) + + return answer diff --git a/merge-two-sorted-lists/hyedall.py b/merge-two-sorted-lists/hyedall.py new file mode 100644 index 0000000000..2b88ef0152 --- /dev/null +++ b/merge-two-sorted-lists/hyedall.py @@ -0,0 +1,31 @@ +""" +https://leetcode.com/problems/merge-two-sorted-lists/description/ + +시간 복잡도 : O(n) +공간 복잡도 : O(1) +""" + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def mergeTwoLists(self, list1: ListNode | None, list2: ListNode | None) -> ListNode | None: + + dummy = ListNode(0) + tail = dummy + + while list1 and list2: + if list1.val <= list2.val: + tail.next = list1 + list1 = list1.next + else: + tail.next = list2 + list2 = list2.next + + tail = tail.next + + tail.next = list1 or list2 + + return dummy.next diff --git a/word-search/hyedall.py b/word-search/hyedall.py new file mode 100644 index 0000000000..45f3e70c11 --- /dev/null +++ b/word-search/hyedall.py @@ -0,0 +1,43 @@ +""" +https://leetcode.com/problems/word-search/description/ + +시간 복잡도 : O(m * n * 3^L * L) +공간 복잡도 : O(m * n + L^2) +""" + +class Solution: + def exist(self, board: list[list[str]], word: str) -> bool: + n, m = len(board[0]), len(board) + + # 상, 하, 좌, 우 + directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] + + stack = [] + + # 시작점 탐색 + for i in range(n): + for j in range(m): + if board[j][i] == word[0]: + stack.append((i, j, 0, {(i, j)})) + + while stack: + x, y, index, visited = stack.pop() + + if index == len(word) - 1: + return True + + for dx, dy in directions: + nx = x + dx + ny = y + dy + + if (0 <= nx < n) and (0 <= ny < m): + if (nx, ny) not in visited: + if board[ny][nx] == word[index + 1]: + stack.append(( + nx, + ny, + index + 1, + visited | {(nx, ny)} + )) + + return False