Golang算法 - Leetcode

 主页   资讯   文章   代码   电子书 

404. Sum of Left Leaves

Leetcode 链接

题目

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题意解析

求所有左叶子节点的和

解决方案

  • 无子节点的称为叶子节点,找出所有的左叶子节点即可

Go 代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func sumOfLeftLeaves(root *TreeNode) int {
    if root == nil || (root.Left == nil && root.Right == nil) {
        return 0
    }

    return helper(root.Left, true) + helper(root.Right, false)
}

func helper(root *TreeNode, isLeft bool ) int {
    if root == nil{
        return 0
    }

    res := 0

    if root.Left == nil && root.Right == nil && isLeft{
        res = root.Val
    }

    res += helper(root.Left, true)
    res += helper(root.Right, false)

    return res
}