Skip to content

Commit cbf5a21

Browse files
committed
1. Maximum Depth of Binary Tree
1 parent e6c6b28 commit cbf5a21

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* 최대 깊이를 탐색하는 문제여서 dfs를 먼저 떠올렸지만 이번에 bfs로 풀이하고 싶어 bfs로 풀었습니다.
4+
*
5+
* n = total node count
6+
* time complexity: O(n)
7+
* space complexity: O(n)
8+
*/
9+
var maxDepth = function (root) {
10+
const queue = [];
11+
let lastIndex = queue.length;
12+
let answer = 0;
13+
14+
if (!root) return answer;
15+
16+
queue.push(root);
17+
18+
while (queue.length !== lastIndex) {
19+
let currentCount = queue.length - lastIndex;
20+
answer++;
21+
22+
while (currentCount--) {
23+
let currentNode = queue[lastIndex];
24+
lastIndex++;
25+
if (currentNode.left) queue.push(currentNode.left);
26+
if (currentNode.right) queue.push(currentNode.right);
27+
}
28+
}
29+
30+
return answer;
31+
};

0 commit comments

Comments
 (0)