forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0104-maximum-depth-of-binary-tree.kt
39 lines (35 loc) · 1.06 KB
/
0104-maximum-depth-of-binary-tree.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.*
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun maxDepth(root: TreeNode?): Int {
if (root == null)
return 0
val left = maxDepth(root.left)
val right = maxDepth(root.right)
return 1 + Math.max(left, right)
}
fun iterativeMaxDepth(root: TreeNode?): Int {
if (root == null) return 0
val callStack = Stack<Pair<TreeNode, Int>>().apply { add(Pair(root, 1)) }
var currentMaxDepth = 1
var temp: Pair<TreeNode, Int>
while (callStack.isNotEmpty()) {
temp = callStack.pop()
currentMaxDepth = maxOf(currentMaxDepth, temp.second)
with(temp.first) {
left?.let { callStack.add(Pair(it, currentMaxDepth + 1)) }
right?.let { callStack.add(Pair(it, currentMaxDepth + 1)) }
}
}
return currentMaxDepth
}
}