给定二叉树的根节点 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/