1302. Deepest Leaves Sum
Previous1269. Number of Ways to Stay in the Same Place After Some StepsNext1310. XOR Queries of a Subarray
Last updated
Last updated
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15func deepestLeavesSum(root *TreeNode) int {
ans, maxHeight := 0, -1
var dfs func(node *TreeNode, h int)
dfs = func(node *TreeNode, h int) {
if node == nil {
return
}
if h > maxHeight {
maxHeight = h
ans = node.Val // update max height along with the deepest leaf
} else if h == maxHeight {
ans += node.Val
}
dfs(node.Left, h+1)
dfs(node.Right, h+1)
}
dfs(root, 0)
return ans
}