Skip to content

Commit b38d4ec

Browse files
committed
maximum-depth-of-binary-tree
1 parent a38f14d commit b38d4ec

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+
* 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+
if (!root) return 0; // ๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฉด ๊นŠ์ด๋Š” 0
15+
16+
// ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ ์กด์žฌํ•˜๋ฏ€๋กœ ๊ธฐ๋ณธ ๊นŠ์ด๋Š” 1
17+
// ์ž์‹์ด ์•„์˜ˆ ์—†๋Š” ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•ด ์ดˆ๊ธฐ๊ฐ’ ์„ค์ •
18+
let left = 1;
19+
let right = 1;
20+
21+
// ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์žˆ์œผ๋ฉด ์žฌ๊ท€์ ์œผ๋กœ ๊นŠ์ด ๊ณ„์‚ฐ ํ›„ ํ˜„์žฌ ๋ ˆ๋ฒจ(+1) ์ถ”๊ฐ€
22+
if (root.left) {
23+
left = maxDepth(root.left) + 1;
24+
}
25+
// ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ์žˆ์œผ๋ฉด ์žฌ๊ท€์ ์œผ๋กœ ๊นŠ์ด ๊ณ„์‚ฐ ํ›„ ํ˜„์žฌ ๋ ˆ๋ฒจ(+1) ์ถ”๊ฐ€
26+
if (root.right) {
27+
right = maxDepth(root.right) + 1;
28+
}
29+
// ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ์ค‘ ๋” ๊นŠ์€ ๊ฐ’์„ ๋ฐ˜ํ™˜
30+
return Math.max(left, right);
31+
};

0 commit comments

Comments
ย (0)