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
Lines changed: 31 additions & 0 deletions
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)