Skip to content

Commit e4deb82

Browse files
committed
feat: 104. Maximum Depth of Binary Tree
1 parent 1a97465 commit e4deb82

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {number}
15+
*/
16+
var maxDepth = function (root) {
17+
let answer = 0;
18+
19+
const dfs = (current, depth) => {
20+
if (!current) {
21+
return;
22+
}
23+
24+
if (answer < depth) {
25+
answer = depth;
26+
}
27+
28+
if (current.left) {
29+
dfs(current.left, depth + 1);
30+
}
31+
32+
if (current.right) {
33+
dfs(current.right, depth + 1);
34+
}
35+
};
36+
37+
dfs(root, 1);
38+
return answer;
39+
};

0 commit comments

Comments
 (0)