版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412972
递归查询左子树是不是叶子节点,是就计入结果中
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func sumOfLeftLeaves(root *TreeNode) int {
sum := 0
if root != nil {
if isLeaf(root.Left) {
sum += root.Left.Val
} else {
sum += sumOfLeftLeaves(root.Left)
}
sum += sumOfLeftLeaves(root.Right)
}
return sum
}
func isLeaf(root *TreeNode) bool {
if root == nil || root.Left != nil || root.Right != nil {
return false
}
return true
}