Skip to content

Commit d7f0126

Browse files
committed
solve: maximum depth of binary tree
1 parent 6b478f3 commit d7f0126

File tree

1 file changed

+39
-0
lines changed
  • maximum-depth-of-binary-tree

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+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number}
12+
*/
13+
var maxDepth = function (root) {
14+
if (root === null) {
15+
return 0;
16+
}
17+
18+
const leftDepth = maxDepth(root.left);
19+
const rightDepth = maxDepth(root.right);
20+
21+
return Math.max(leftDepth, rightDepth) + 1;
22+
};
23+
24+
/**
25+
* Time Complexity: O(n), where n is the number of nodes in the binary tree.
26+
* Reason:
27+
* the function visits each node exactly once in order to compute the depth of the tree,
28+
* which ensures that each node is processed a single time.
29+
*
30+
* Space Complexity: O(h), where h is the height of the binary tree.
31+
* Reason:
32+
* The recursion stack used during the depth-first traversal.
33+
*
34+
* In the worst case, where the tree is completely unbalanced,
35+
* the height h can be equal to the number of nodes n, leading to a space complexity of O(n).
36+
*
37+
* In the best case, where the tree is balanced, the height h is log(n),
38+
* leading to a space complexity of O(log(n)).
39+
*/

0 commit comments

Comments
 (0)