Skip to content

Commit b675740

Browse files
Create 0104. Maximum Depth of Binary Tree.md
1 parent 786df9a commit b675740

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Trees
2+
![Screen Shot 2023-03-11 at 4 08 21 PM](https://user-images.githubusercontent.com/37787994/224513536-6951e8d3-9ce9-4658-bd81-9ad0ecf430c9.png)
3+
4+
Time Complexity:
5+
The time complexity of this code is **O(n)**, where n is the number of nodes in the binary tree. This is because the code recursively visits each node in the binary tree exactly once, and performs a constant amount of work at each node.
6+
7+
Space Complexity:
8+
The space complexity of this code is **O(h)**, where h is the height of the binary tree. This is because the code uses a recursive algorithm to traverse the binary tree, and the maximum depth of the recursive call stack is equal to the height of the tree. Therefore, in the worst case, the space required by the call stack is proportional to the height of the tree.
9+
10+
```js
11+
/**
12+
* Definition for a binary tree node.
13+
* function TreeNode(val, left, right) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.left = (left===undefined ? null : left)
16+
* this.right = (right===undefined ? null : right)
17+
* }
18+
*/
19+
/**
20+
* @param {TreeNode} root
21+
* @return {number}
22+
*/
23+
var maxDepth = function(root) {
24+
if(!root) return null;
25+
let leftDepth = maxDepth(root.left);
26+
let rightDepth = maxDepth(root.right);
27+
return Math.max(leftDepth, rightDepth) + 1;
28+
};
29+
```

0 commit comments

Comments
 (0)