File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * DFS
3+ * Time complexity: O(n)
4+ * Space complexity: O(h) - h is the height of the tree, worst case O(n)
5+ */
6+ const maxDepth = ( root ) => {
7+ if ( root === null ) return 0 ;
8+
9+ const leftDepth = maxDepth ( root . left ) ;
10+ const rightDepth = maxDepth ( root . right ) ;
11+
12+ return 1 + Math . max ( leftDepth , rightDepth ) ;
13+ } ;
14+
15+ /**
16+ * BFS
17+ * Time complexity: O(n)
18+ * Space complexity: O(n)
19+ */
20+ const maxDepthBFS = ( root ) => {
21+ if ( root === null ) return 0 ;
22+
23+ const queue = [ root ] ;
24+ let depth = 0 ;
25+
26+ while ( queue . length > 0 ) {
27+ const levelSize = queue . length ;
28+
29+ for ( let i = 0 ; i < levelSize ; i ++ ) {
30+ const node = queue . shift ( ) ;
31+ if ( node . left ) queue . push ( node . left ) ;
32+ if ( node . right ) queue . push ( node . right ) ;
33+ }
34+
35+ depth ++ ;
36+ }
37+
38+ return depth ;
39+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * 1. Recursive approach
3+ * Time complexity: O(n + m)
4+ * Space complexity: O(n + m)
5+ */
6+ // const mergeTwoLists = (list1, list2) => {
7+ // if (!list1) return list2;
8+ // if (!list2) return list1;
9+ //
10+ // if (list1.val <= list2.val) {
11+ // list1.next = mergeTwoLists(list1.next, list2);
12+ // return list1;
13+ // } else {
14+ // list2.next = mergeTwoLists(list1, list2.next);
15+ // return list2;
16+ // }
17+ // };
18+
19+ /**
20+ * 2. Iterative approach + Dummy Node
21+ * Time complexity: O(n + m)
22+ * Space complexity: O(1)
23+ */
24+ const mergeTwoLists = ( list1 , list2 ) => {
25+ const dummy = new ListNode ( - 1 ) ;
26+ let current = dummy ;
27+
28+ while ( list1 !== null && list2 !== null ) {
29+ if ( list1 . val <= list2 . val ) {
30+ current . next = list1 ;
31+ list1 = list1 . next ;
32+ } else {
33+ current . next = list2 ;
34+ list2 = list2 . next ;
35+ }
36+ current = current . next ;
37+ }
38+
39+ current . next = list1 ?? list2 ;
40+
41+ return dummy . next ;
42+ } ;
You can’t perform that action at this time.
0 commit comments