Skip to content

Commit 4b8d6d5

Browse files
committed
Added maximum depth of bt solution
1 parent d769f97 commit 4b8d6d5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
// Check root is null or not
15+
if (root === null) {
16+
return 0;
17+
}
18+
// Make queue array to store root and depth variable
19+
let queue = [root];
20+
let depth = 0;
21+
// Iterate until there is an element inside of queue
22+
while (queue.length > 0) {
23+
// Record level size to avoid fault size measuring
24+
let levelSize = queue.length;
25+
26+
for (let i = 0; i < levelSize; i++) {
27+
// Grasp first element from the queue
28+
const node = queue.shift();
29+
// Push the left node into the queue
30+
if (node.left) {
31+
queue.push(node.left);
32+
}
33+
// Push the right node into the queue
34+
if (node.right) {
35+
queue.push(node.right);
36+
}
37+
}
38+
// Increase depth value
39+
depth++;
40+
}
41+
42+
return depth;
43+
};
44+
45+
// TC: O(n)
46+
// SC: O(n)

0 commit comments

Comments
 (0)