Here’s another shot at a tree traversal problem. This solution uses Depth-First Traversal.
/**
* 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 {
var min = 0
fun minDepth(root: TreeNode?): Int {
if(root == null) return 0
if(root?.left == null) return minDepth(root?.right) + 1
if(root?.right == null) return minDepth(root?.left) + 1
return Math.min(minDepth(root?.left), minDepth(root?.right)) + 1
}
}
Runtime: 180 ms, faster than 41.67% of Kotlin online submissions for Minimum Depth of Binary Tree.
Memory Usage: 35 MB, less than 100.00% of Kotlin online submissions for Minimum Depth of Binary Tree.