diff --git a/maximum-depth-of-binary-tree/1lsang.ts b/maximum-depth-of-binary-tree/1lsang.ts new file mode 100644 index 0000000000..c58100e360 --- /dev/null +++ b/maximum-depth-of-binary-tree/1lsang.ts @@ -0,0 +1,35 @@ +/** + * 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 { + // DFS (혹은 BFS) 후 깊이 체크하기 + if (!root) return 0; + + const stack: [TreeNode, number][] = [[root, 1]]; + let maxDepth = 0; + + while (stack.length > 0) { + const [node, depth] = stack.pop()!; + maxDepth = Math.max(maxDepth, depth); + + if (node.right) { + stack.push([node.right, depth + 1]); + } + if (node.left) { + stack.push([node.left, depth + 1]); + } + } + + return maxDepth; +}; diff --git a/merge-two-sorted-lists/1lsang.ts b/merge-two-sorted-lists/1lsang.ts new file mode 100644 index 0000000000..bf07cf2c20 --- /dev/null +++ b/merge-two-sorted-lists/1lsang.ts @@ -0,0 +1,54 @@ +/** + * 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) + * } + * } + */ + +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 { + // list1과 list2의 val을 비교해나가면서 새로운 list 생성 + // 1. list1 없으면 list2 return + if (!list1) return list2; + // 2. list2 없으면 list1 return + if (!list2) return list1; + + const list = new ListNode(-101); + + let listNode = list; + let listNode1: ListNode | null = list1; + let listNode2: ListNode | null = list2; + + while (listNode1 && listNode2) { + if (listNode1.val > listNode2.val) { + listNode.next = new ListNode(listNode2.val, null); + listNode2 = listNode2.next; + } + else { + listNode.next = new ListNode(listNode1.val, null); + listNode1 = listNode1.next; + } + listNode = listNode.next; + } + if (!listNode1) { + listNode.next = listNode2; + } + else if (!listNode2) { + listNode.next = listNode1; + } + + return list.next; +};