diff --git a/maximum-depth-of-binary-tree/wozlsla.py b/maximum-depth-of-binary-tree/wozlsla.py new file mode 100644 index 000000000..8ab8b4c5d --- /dev/null +++ b/maximum-depth-of-binary-tree/wozlsla.py @@ -0,0 +1,59 @@ +""" +# Intuition +트리 전체 순회 + +# Approach +- + +# Complexity +time : O(N) +space : 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 + + +# Stack (top-down) +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + + # edge case + if not root: + return 0 + + max_depth = 0 + stack = [(root, 1)] + + while stack: + node, depth = stack.pop() + + max_depth = max(depth, max_depth) # update depth + + if node.left: + stack.append((node.left, depth + 1)) + if node.right: + stack.append((node.right, depth + 1)) + + return max_depth + + +""" 재귀 (bottom-top) +# max_depth : 현재 노드를 기준으로, 좌측과 우측 자식 트리 중 max_depth가 큰 값을 선택해 + 1 + +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + + # 기저조건 + if not root: + return 0 + + return 1 + max( + self.maxDepth(root.left), + self.maxDepth(root.right), + ) +""" diff --git a/merge-two-sorted-lists/wozlsla.py b/merge-two-sorted-lists/wozlsla.py new file mode 100644 index 000000000..ff283a55d --- /dev/null +++ b/merge-two-sorted-lists/wozlsla.py @@ -0,0 +1,85 @@ +""" +# Intuition +- +# Approach +- +# Complexity +time : O(N+M) +space : O(1) / O(N+M) +""" + +from typing import Optional + + +# 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: Optional[ListNode], list2: Optional[ListNode] + ) -> Optional[ListNode]: + + dummy = ListNode(None) # -> None(고정) + node = dummy # -> None(이동) + + while list1 and list2: + + if list1.val < list2.val: + node.next = list1 + list1 = list1.next + else: + node.next = list2 + list2 = list2.next + + node = node.next # (이동) + + # 반복문 종료 + node.next = list1 or list2 + + return dummy.next # 병합 리스트의 첫 번째 노드를 가리킴 + + +# list1: 1 -> 2 -> 4 +list1_node3 = ListNode(4) +list1_node2 = ListNode(2, list1_node3) +list1_node1 = ListNode(1, list1_node2) + +# list2: 1 -> 3 -> 4 +list2_node3 = ListNode(4) +list2_node2 = ListNode(3, list2_node3) +list2_node1 = ListNode(1, list2_node2) + +sol = Solution() +merged_list = sol.mergeTwoLists(list1_node1, list2_node1) + +# 결과 출력 +current = merged_list +result = [] +while current: + result.append(current.val) + current = current.next + +print(result) + + +""" 재귀 +class Solution: + def mergeTwoLists( + self, list1: Optional[ListNode], list2: Optional[ListNode] + ) -> Optional[ListNode]: + + # 기저조건 + if not (list1 and list2): + return list1 or list2 + + if list1.val < list2.val: + list1.next = self.mergeTwoLists(list1.next, list2) + return list1 + else: + list2.next = self.mergeTwoLists(list1, list2.next) + return list2 +"""