Skip to content

Commit 1e321a7

Browse files
committed
Add maximum depth of binary tree solution
1 parent 409c862 commit 1e321a7

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
2+
// - n: ํŠธ๋ฆฌ์˜ ๋…ธ๋“œ ๊ฐœ์ˆ˜
3+
// - ๊ฐ ๋…ธ๋“œ๋ฅผ ์ •ํ™•ํžˆ ํ•œ ๋ฒˆ์”ฉ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ O(n)
4+
//
5+
// ๊ณต๊ฐ„ ๋ณต์žก๋„: O(h)
6+
// - h: ํŠธ๋ฆฌ์˜ ๋†’์ด
7+
// - ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ์— ์ตœ๋Œ€ h๊ฐœ์˜ ํ•จ์ˆ˜ ํ˜ธ์ถœ์ด ์Œ“์ž„
8+
// - ์ตœ์•…์˜ ๊ฒฝ์šฐ(ํŽธํ–ฅ ํŠธ๋ฆฌ) h = n ์ด๋ฏ€๋กœ O(n),
9+
// ์ตœ์„ ์˜ ๊ฒฝ์šฐ(๊ท ํ˜• ํŠธ๋ฆฌ) h = log n ์ด๋ฏ€๋กœ O(log n)
10+
11+
class Solution {
12+
fun maxDepth(root: TreeNode?): Int {
13+
if (root == null) return 0
14+
15+
val leftDepth = maxDepth(root.left)
16+
val rightDepth = maxDepth(root.right)
17+
18+
return maxOf(leftDepth, rightDepth) + 1
19+
}
20+
}

0 commit comments

Comments
ย (0)