Skip to content

Commit 2c306f3

Browse files
committed
Maximum Depth of Binary Tree solution
1 parent 9be4f2b commit 2c306f3

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+
* ๋ฌธ์ œ ์š”์•ฝ: ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, ์ด ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค
3+
* ์ตœ๋Œ€ ๊นŠ์ด: ๋ฃจํŠธ ๋…ธ๋“œ์—์„œ ๊ฐ€์žฅ ๋จผ ๋ฆฌํ”„ ๋…ธ๋“œ๊นŒ์ง€์˜ ๊ฒฝ๋กœ์— ์žˆ๋Š” ๋…ธ๋“œ์˜ ์ˆ˜
4+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n) - ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธ
5+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(h) - h๋Š” ํŠธ๋ฆฌ์˜ ๋†’์ด(์ตœ์•…์˜ ๊ฒฝ์šฐ O(n)) - ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ ์‚ฌ์šฉ
6+
*/
7+
8+
/**
9+
* Definition for a binary tree node.
10+
* function TreeNode(val, left, right) {
11+
* this.val = (val===undefined ? 0 : val)
12+
* this.left = (left===undefined ? null : left)
13+
* this.right = (right===undefined ? null : right)
14+
* }
15+
*/
16+
/**
17+
* @param {TreeNode} root
18+
* @return {number}
19+
*/
20+
var maxDepth = function (root) {
21+
// ๊ธฐ์ € ์กฐ๊ฑด: ๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฉด(empty tree) ๊นŠ์ด๋Š” 0
22+
if (root === null) {
23+
return 0;
24+
}
25+
26+
const leftDepth = maxDepth(root.left);
27+
const rightDepth = maxDepth(root.right);
28+
29+
// ํ˜„์žฌ ๋…ธ๋“œ์˜ ์ตœ๋Œ€ ๊นŠ์ด: ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด ์ค‘ ํฐ ๊ฐ’์— 1์„ ๋”ํ•œ ๊ฐ’
30+
return Math.max(leftDepth, rightDepth) + 1;
31+
};

0 commit comments

Comments
ย (0)