diff --git a/maximum-subarray/reeseo3o.js b/maximum-subarray/reeseo3o.js new file mode 100644 index 0000000000..1332a6f056 --- /dev/null +++ b/maximum-subarray/reeseo3o.js @@ -0,0 +1,39 @@ +/** + * DFS + * Time complexity: O(n) + * Space complexity: O(h) - h is the height of the tree, worst case O(n) + */ +const maxDepth = (root) => { + if (root === null) return 0; + + const leftDepth = maxDepth(root.left); + const rightDepth = maxDepth(root.right); + + return 1 + Math.max(leftDepth, rightDepth); +}; + +/** + * BFS + * Time complexity: O(n) + * Space complexity: O(n) + */ +const maxDepthBFS = (root) => { + if (root === null) return 0; + + const queue = [root]; + let depth = 0; + + while (queue.length > 0) { + const levelSize = queue.length; + + for (let i = 0; i < levelSize; i++) { + const node = queue.shift(); + if (node.left) queue.push(node.left); + if (node.right) queue.push(node.right); + } + + depth++; + } + + return depth; +}; diff --git a/merge-two-sorted-lists/reeseo3o.js b/merge-two-sorted-lists/reeseo3o.js new file mode 100644 index 0000000000..7b613d7802 --- /dev/null +++ b/merge-two-sorted-lists/reeseo3o.js @@ -0,0 +1,42 @@ +/** + * 1. Recursive approach + * Time complexity: O(n + m) + * Space complexity: O(n + m) + */ +// const mergeTwoLists = (list1, list2) => { +// if (!list1) return list2; +// if (!list2) return list1; +// +// if (list1.val <= list2.val) { +// list1.next = mergeTwoLists(list1.next, list2); +// return list1; +// } else { +// list2.next = mergeTwoLists(list1, list2.next); +// return list2; +// } +// }; + +/** + * 2. Iterative approach + Dummy Node + * Time complexity: O(n + m) + * Space complexity: O(1) + */ +const mergeTwoLists = (list1, list2) => { + const dummy = new ListNode(-1); + 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 ?? list2; + + return dummy.next; +};