Array - Array Rotation
Array- CountTripletsSmallerThanSum

Leetcode - deepest-leaves-sum

violet posted @ Feb 25, 2020 05:57:31 AM in 算法 with tags tree Algorithm Golang , 233 阅读

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
}

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter