leetcode 404. 左叶子之和

题解

找出左叶子节点,可以通过叶子节点的父节点进行判断

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sumOfLeftLeaves(root *TreeNode) int {
res := 0
if root == nil {
return 0
}
if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
res += root.Left.Val
}
if root.Left != nil {
res += sumOfLeftLeaves(root.Left)
}
if root.Right != nil {
res += sumOfLeftLeaves(root.Right)
}
return res
}