Skip to content

Commit 4574e94

Browse files
committed
Feat: 104. Maximum Depth of Binary Tree
1 parent 3c980d6 commit 4574e94

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// class TreeNode {
2+
// val: number;
3+
// left: TreeNode | null;
4+
// right: TreeNode | null;
5+
// constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
// this.val = val === undefined ? 0 : val;
7+
// this.left = left === undefined ? null : left;
8+
// this.right = right === undefined ? null : right;
9+
// }
10+
// }
11+
12+
/**
13+
* https://leetcode.com/problems/maximum-depth-of-binary-tree
14+
* using recursion
15+
* T.C. O(n)
16+
* S.C. O(n)
17+
*/
18+
function maxDepth(root: TreeNode | null): number {
19+
return dfs(root, 0);
20+
}
21+
22+
function dfs(node: TreeNode | null, depth: number): number {
23+
if (!node) {
24+
return depth;
25+
}
26+
return Math.max(dfs(node.left, depth + 1), dfs(node.right, depth + 1));
27+
}
28+
29+
/**
30+
* using stack
31+
* T.C. O(n)
32+
* S.C. O(n)
33+
*/
34+
function maxDepth(root: TreeNode | null): number {
35+
if (!root) {
36+
return 0;
37+
}
38+
39+
let max = 0;
40+
41+
const stack: [TreeNode | null, number][] = [];
42+
stack.push([root, 1]);
43+
44+
while (stack.length) {
45+
const [node, depth] = stack.pop()!;
46+
47+
if (node) {
48+
max = Math.max(max, depth);
49+
stack.push([node.left, depth + 1]);
50+
stack.push([node.right, depth + 1]);
51+
}
52+
}
53+
54+
return max;
55+
}

0 commit comments

Comments
 (0)