Skip to content

Commit 8ea2c0d

Browse files
committed
solution Maximum Depth of Binary Tree (#227)
- #227
1 parent e706586 commit 8ea2c0d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* val: number
5+
* left: TreeNode | null
6+
* right: TreeNode | null
7+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8+
* this.val = (val===undefined ? 0 : val)
9+
* this.left = (left===undefined ? null : left)
10+
* this.right = (right===undefined ? null : right)
11+
* }
12+
* }
13+
*/
14+
15+
function maxDepth(root: TreeNode | null): number {
16+
// ๊ธฐ๋ณธ ์ผ€์ด์Šค: ๋…ธ๋“œ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ๊นŠ์ด๋Š” 0
17+
if (root === null) {
18+
return 0;
19+
}
20+
21+
// ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด
22+
const leftDepth = maxDepth(root.left);
23+
24+
// ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด
25+
const rightDepth = maxDepth(root.right);
26+
27+
// ํ˜„์žฌ ๋…ธ๋“œ์˜ ๊นŠ์ด๋Š” ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ์ค‘ ๋” ๊นŠ์€ ๊ฒƒ์— 1์„ ๋”ํ•œ ๊ฐ’
28+
return Math.max(leftDepth, rightDepth) + 1;
29+
}

0 commit comments

Comments
ย (0)