Skip to content

Commit 125a14c

Browse files
committed
solve: maximum depth of binary tree
1 parent 42c0ba4 commit 125a14c

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+
* TC: O(N)
3+
* 모든 노드를 순회합니다.
4+
*
5+
* SC: O(N)
6+
* 노드의 수에 비례해서 queue의 길이가 증가됩니다.
7+
*
8+
* N: count of tree node
9+
*/
10+
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+
let maximumDepth = 0;
25+
26+
const queue = [[root, 1]];
27+
while (queue.length > 0) {
28+
const [current, depth] = queue.shift();
29+
30+
if (current === null) {
31+
break;
32+
}
33+
34+
maximumDepth = Math.max(maximumDepth, depth);
35+
36+
if (current.left) {
37+
queue.push([current.left, depth + 1]);
38+
}
39+
40+
if (current.right) {
41+
queue.push([current.right, depth + 1]);
42+
}
43+
}
44+
45+
return maximumDepth;
46+
};

0 commit comments

Comments
 (0)