404. 左叶子之和(javascript)404. Sum of Left Leaves

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

Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

示例 1:

请添加图片描述

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

示例 2:

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

判断是不是叶子节点,如果是叶子节点并且是左子树的叶子节点就把它的值加入sum中

var sumOfLeftLeaves = function (root) {
    let sum = 0
    var leaves = function (root) {
        if (!root) return;//为空节点,判空处理
        //是左子节点  并且左子节点的左右节点都为空 也就是说是叶子节点
        if (root.left && root.left.left == null && root.left.right == null) {
        	//叶子节点,root.left.val代表左孩子的值
            sum += root.left.val
        }
        leaves(root.left)//递归左子树
        leaves(root.right)//递归右子树
    };
    leaves(root)
    return sum
};

leetcode:https://leetcode-cn.com/problems/sum-of-left-leaves/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值