404. Sum of Left Leaves
题干简述:
给我们一个二叉树的根节点,求该二叉树所有左叶子节点的和。
叶子节点,即没有子节点的节点。
解题思路
求解二叉树的所有左叶子节点的和,我们需要累加所有左子节点的值,因此我们需要知道哪些节点是叶左子节点。如果是左叶子节点,就把它的值加起来;如果不是,对左子树进行递归操作即可。
题解
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumOfLeftLeaves = function(root) {
if (!root) return 0;
let res = 0;
if (isLeaf(root.left)) {
res += root.left.val + sumOfLeftLeaves(root.right);
} else {
res += sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
return res;
};
const isLeaf = function (node) {
if (!node) return false;
return !node.left && !node.right;
}
Q.E.D.