Leetcode - deepest-leaves-sum
https://leetcode.com/problems/deepest-leaves-sum
Given a binary tree, return the sum of values of its deepest leaves.
The though is very simple. Use a level order traversal when at the bottom, sum all value.
We've known how to do level order traversal, just update it a bit. Let it break when meeting the bottom of the tree.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func deepestLeavesSum(root *TreeNode) int { if root == nil { return 0 } queue := []*TreeNode{root} sum := 0 for len(queue) != 0 { size := len(queue) sum = 0 for i := 0; i < size; i++ { node := queue[i] sum += node.Val if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } } queue = queue[size:] } return sum }