Skip to content

Instantly share code, notes, and snippets.

@yushman
Created July 1, 2021 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yushman/a818eb5fb59f156d5763b694a230df33 to your computer and use it in GitHub Desktop.
Save yushman/a818eb5fb59f156d5763b694a230df33 to your computer and use it in GitHub Desktop.
class Solution {
val leaves = mutableListOf<Pair<TreeNode, Int>>()
var depth = 1
fun deepestLeavesSum(root: TreeNode?): Int {
if (root == null) return 0
calcdepth(root)
val maxdepth = leaves.map { it.second }.maxBy { it }
return leaves.filter { it.second == maxdepth }.sumBy { it.first.`val` }
}
private fun calcdepth(root: TreeNode) {
if (root.left == null && root.right == null) {
leaves.add(Pair(root, depth--))
return
}
if (root.left != null) {
depth++
calcdepth(root.left!!)
}
if (root.right != null) {
depth++
calcdepth(root.right!!)
}
if (root.left == null || root.right == null) depth--
if (root.left != null && root.right != null) depth--
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment