Skip to content

404. 左叶子之和

leetcode-cn.comproblemssum-of-left-leaves (1).png

js
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumOfLeftLeaves = function (root) {
  if (!root) return 0;

  // 左子树 左叶子之和
  const leftSum = sumOfLeftLeaves(root.left);
  // 右子树 左叶子之和
  const rightSum = sumOfLeftLeaves(root.right);

  let val = 0;
  // 当前节点左叶子
  if (root.left && !root.left.left && !root.left.right) {
    val = root.left.val;
  }
  return leftSum + rightSum + val;
};
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumOfLeftLeaves = function (root) {
  if (!root) return 0;

  // 左子树 左叶子之和
  const leftSum = sumOfLeftLeaves(root.left);
  // 右子树 左叶子之和
  const rightSum = sumOfLeftLeaves(root.right);

  let val = 0;
  // 当前节点左叶子
  if (root.left && !root.left.left && !root.left.right) {
    val = root.left.val;
  }
  return leftSum + rightSum + val;
};