Skip to content

Commit 68408c9

Browse files
committed
week4: maximum-subarray
1 parent 9fac6a2 commit 68408c9

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

maximum-subarray/reeseo3o.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Time complexity: O(n)
3+
* Space complexity: O(h) - h is the height of the tree, worst case O(n)
4+
*/
5+
const maxDepth = (root) => {
6+
if (root === null) return 0;
7+
8+
const leftDepth = maxDepth(root.left);
9+
const rightDepth = maxDepth(root.right);
10+
11+
return 1 + Math.max(leftDepth, rightDepth);
12+
};
13+
14+
// BFS - TC: O(n) | SC: O(n)
15+
const maxDepthBFS = (root) => {
16+
if (root === null) return 0;
17+
18+
const queue = [root];
19+
let depth = 0;
20+
21+
while (queue.length > 0) {
22+
const levelSize = queue.length;
23+
24+
for (let i = 0; i < levelSize; i++) {
25+
const node = queue.shift();
26+
if (node.left) queue.push(node.left);
27+
if (node.right) queue.push(node.right);
28+
}
29+
30+
depth++;
31+
}
32+
33+
return depth;
34+
};

0 commit comments

Comments
 (0)