/**
* Good morning! Here's your coding interview problem for today.
This problem was asked by Google. Given the root of a binary tree, return a deepest node.
* */
class TreeNode(var value: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
class Problem_622 {
/*
* soluton DFS: 1. find the height of the tree, 2.scan level by level;
* Time complexity:O(n), Space complexity:O(1)
* */
var deepest = 0
fun findDeepest(root: TreeNode?): Int {
if (root == null) {
return 0
}
val level = getHeight(root)
findDeepest(root, level)
return deepest
}
private fun findDeepest(root: TreeNode?, level: Int) {
if (root != null) {
if (level == 1) {
deepest = root.value
} else if (level > 1) {
findDeepest(root.left, level - 1)
findDeepest(root.right, level - 1)
}
}
}
private fun getHeight(root: TreeNode?): Int {
if (root == null) {
return 0
}
val leftHeight = getHeight(root.left)
val rightHeight = getHeight(root.right)
return Math.max(leftHeight, rightHeight) + 1
}
}