diff --git a/maximum-depth-of-binary-tree/jiji-hoon96.ts b/maximum-depth-of-binary-tree/jiji-hoon96.ts new file mode 100644 index 000000000..343a1f5c4 --- /dev/null +++ b/maximum-depth-of-binary-tree/jiji-hoon96.ts @@ -0,0 +1,29 @@ +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function maxDepth(root: TreeNode | null): number { + // 기본 케이스: 노드가 없는 경우 깊이는 0 + if (root === null) { + return 0; + } + + // 왼쪽 서브트리의 최대 깊이 + const leftDepth = maxDepth(root.left); + + // 오른쪽 서브트리의 최대 깊이 + const rightDepth = maxDepth(root.right); + + // 현재 노드의 깊이는 왼쪽과 오른쪽 서브트리 중 더 깊은 것에 1을 더한 값 + return Math.max(leftDepth, rightDepth) + 1; +} diff --git a/merge-two-sorted-lists/jiji-hoon96.ts b/merge-two-sorted-lists/jiji-hoon96.ts new file mode 100644 index 000000000..c0b375f9b --- /dev/null +++ b/merge-two-sorted-lists/jiji-hoon96.ts @@ -0,0 +1,35 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null { + // 더미 헤드 노드를 생성하여 결과 리스트의 시작점으로 사용 + const dummy = new ListNode(0); + let current = dummy; + + // 두 리스트를 순회하면서 더 작은 값을 가진 노드를 결과 리스트에 연결 + while (list1 !== null && list2 !== null) { + if (list1.val <= list2.val) { + current.next = list1; + list1 = list1.next; + } else { + current.next = list2; + list2 = list2.next; + } + current = current.next; + } + + // 남은 노드들을 결과 리스트에 연결 + current.next = list1 === null ? list2 : list1; + + // 더미 노드의 다음 노드가 실제 병합된 리스트의 헤드 + return dummy.next; +}