Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1161 from t3chkid/main
Browse files Browse the repository at this point in the history
Adds iterative solution to 104. Maximum Depth of Binary Tree in Kotlin
  • Loading branch information
Ahmad-A0 authored Sep 24, 2022
2 parents 69f7d5d + 9fd6ddf commit 7186a2a
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions kotlin/104-Maximum-Depth-Of-Binary-Tree.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import java.util.*

/**
* Example:
* var ti = TreeNode(5)
Expand All @@ -18,4 +20,20 @@ class Solution {

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
}
}

0 comments on commit 7186a2a

Please sign in to comment.