Skip to content

Commit 8a4d98e

Browse files
author
แ„‹แ…ตแ„‹แ…งแ†ซแ„‰แ…ฎ
committed
maximum depth of binary tree
1 parent 687e199 commit 8a4d98e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package leetcode_study
2+
3+
/*
4+
* ์ด์ง„ ํŠธ๋ฆฌ์˜ ์ตœ๋Œ€ ๊นŠ์ด๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ
5+
* ์žฌ๊ท€๋ฅผ ์‚ฌ์šฉํ•ด ๋ฌธ์ œ ํ•ด๊ฒฐ
6+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
7+
* -> ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ
8+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(n) ํ˜น์€ O(log n)
9+
* -> findDepth() ํ•จ์ˆ˜๋Š” ์žฌ๊ท€์ ์œผ๋กœ ํ˜ธ์ถœ๋˜์–ด ์ฝœ ์Šคํƒ์— ์Œ“์ž„
10+
* -> ๊ท ํ˜•์žกํžŒ ์ด์ง„ํŠธ๋ฆฌ์˜ ๊ฒฝ์šฐ ์žฌ๊ท€์˜ ๊นŠ์ด๋Š” O(log n) ์†Œ์š”
11+
* -> ํŽธํ–ฅ๋œ ์ด์ง„ํŠธ๋ฆฌ์˜ ๊ฒฝ์šฐ ์žฌ๊ท€์˜ ๊นŠ์ด๋Š” O(n) ์†Œ์š”
12+
* */
13+
fun maxDepth(root: TreeNode?): Int {
14+
if (root == null) return 0
15+
val maxValue = findDepth(root, 1) // ์‹œ์ž‘ ๊นŠ์ด ๊ฐ’์€ `1`
16+
return maxValue
17+
}
18+
19+
fun findDepth(currentNode: TreeNode?, depth: Int): Int{
20+
// escape condition
21+
if (currentNode == null) {
22+
return depth - 1
23+
}
24+
25+
val leftValue = findDepth(currentNode.left, depth + 1)
26+
val rightValue = findDepth(currentNode.right, depth + 1)
27+
return maxOf(leftValue, rightValue)
28+
}

0 commit comments

Comments
ย (0)