Skip to content

Commit fa7a304

Browse files
committed
Add maximum-depth-of-binary-tree solution
1 parent 203ebfd commit fa7a304

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Depth-First Search (DFS) with recursion
2+
3+
// 🕒 Time Complexity: O(n) — where n is the number of nodes in the binary tree.
4+
// 🗂️ Space Complexity: O(h) — where h is the height of the tree.
5+
// ⚙️ How It Works (Example Walkthrough):
6+
// For root = [3,9,20,null,null,15,7]:
7+
// maxDepth(root) = Math.max(maxDepth(9), maxDepth(20)) + 1 = Math.max(1, 2) + 1 = 3
8+
// maxDepth(9) = Math.max(maxDepth(null), maxDepth(null)) + 1 = 1
9+
// maxDepth(20) = Math.max(maxDepth(15), maxDepth(7)) + 1 = Math.max(1, 1) + 1 = 2
10+
// maxDepth(15) = Math.max(maxDepth(null), maxDepth(null)) + 1 = 1
11+
// maxDepth(7) = Math.max(maxDepth(null), maxDepth(null)) + 1 = 1
12+
// So the final result: 3
13+
14+
/**
15+
* Definition for singly-linked list.
16+
* function ListNode(val, next) {
17+
* this.val = val === undefined ? 0 : val;
18+
* this.next = next === undefined ? null : next;
19+
* }
20+
*/
21+
/**
22+
* @param {ListNode[]} lists
23+
* @return {ListNode}
24+
*/
25+
26+
// For maximum depth, the presence of one child doesn't matter much because we are looking for the deepest path from the root to any leaf.
27+
var maxDepth = function (root) {
28+
// Base case: if the node is null, the depth is 0
29+
if (root === null) return 0;
30+
31+
// Recursively calculate the depth of the left and right subtrees
32+
let leftDepth = maxDepth(root.left);
33+
let rightDepth = maxDepth(root.right);
34+
35+
// Return the maximum of the two depths plus 1 for the current node
36+
return Math.max(leftDepth, rightDepth) + 1;
37+
};

0 commit comments

Comments
 (0)