404.左嫩叶之和(javascript)404.SumofLeftLeaves
原创给定二叉树的根节点 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
解释: 在这个二叉树中,分别有两个左叶 9 和 15,所以返回。 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/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123



