404. 左叶子之和

leecode原题

题目

给定二叉树的根节点 root ,返回所有左叶子之和。

示例

示例 1:

输入: root = [3,9,20,null,null,15,7] 
输出: 24 
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

示例 2:

输入: root = [1]
输出: 0

提示:

  • 节点数在 [1, 1000] 范围内
  • -1000 <= Node.val <= 1000

解题思路

思路

左叶子的明确定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点

实现

源码

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func travel(root *TreeNode, res *int) {
    // 判断是左叶子节点
    // 这里条件很重要!!!!!, 主要是判断左叶子节点
    if root.Left != nil && root.Left.Left == nil && root.Left.Right == nil {
        *res = *res + root.Left.Val
    }
    if root.Left != nil {
        travel(root.Left, res)
    }
    if root.Right != nil {
        travel(root.Right, res)
    }
}

func sumOfLeftLeaves(root *TreeNode) int {
    res := 0
    if root == nil {
        return res
    }
    travel(root, &res)
    return res
}
Copyright © ROSEMARY666 2022 all right reserved,powered by Gitbook该文章修订时间: 2022-09-28 15:55:21

results matching ""

    No results matching ""