1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumOfLeftLeaves(root *TreeNode) int {
// 直接层序遍历,将叶子结点的值相加即可
var total int
if root == nil {
return total
}
queue := []*TreeNode{root}
for len(queue) > 0 {
curr := queue[0]
queue = queue[1:]
if curr.Left != nil {
queue = append(queue, curr.Left)
// 这一条件保证是叶子结点
if curr.Left.Left == nil && curr.Left.Right == nil {
total += curr.Left.Val
}
}
if curr.Right != nil {
queue = append(queue, curr.Right)
}
}
return total
}
|