Created
July 1, 2021 20:26
-
-
Save yushman/a818eb5fb59f156d5763b694a230df33 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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