Another tree traversal easy LC problem.
class Solution {
fun maxDepth(root: TreeNode?): Int {
if (root == null) return 0
fun maxDepth_(node: TreeNode?, depth: Int): Int {
return if (node == null) depth - 1 else Math.max(
maxDepth_(node.left, depth + 1),
maxDepth_(node.right, depth + 1)
)
}
return maxDepth_(root, 1)
}
}
The idea here is to get the maximum value between the left and right child nodes which will be done recursively for each and every node.
Runtime: 160 ms, faster than 91.84% of Kotlin online submissions for Maximum Depth of Binary Tree.
Memory Usage: 34.5 MB, less than 100.00% of Kotlin online submissions for Maximum Depth of Binary Tree.