Skip to content
On this page

404. 左叶子之和

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

示例 1:

 3
/ \
9 20
  / \
 15 7

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

示例  2:
输入: root = [1]
输出: 0

提示:
节点数在  [1, 1000]  范围内
-1000 <= Node.val <= 1000

javascript
/**
 * 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) {
  var res = 0
  function preOrder(root) {
    if (root) {
      if (root.left && !root.left.left && !root.left.right) res += root.left.val
      preOrder(root.left)
      preOrder(root.right)
    }
  }
  preOrder(root)
  return res
}

// test
function TreeNode(val, left, right) {
  this.val = val === undefined ? 0 : val
  this.left = left === undefined ? null : left
  this.right = right === undefined ? null : right
}

// var n1 = new TreeNode(3)
// var n2 = new TreeNode(9)
// var n3 = new TreeNode(20)
// var n4 = new TreeNode(15)
// var n5 = new TreeNode(7)
// n1.left = n2
// n1.right = n3
// n3.left = n4
// n3.right = n5

// console.log(sumOfLeftLeaves(n1))

var n1 = new TreeNode(1)
var n2 = new TreeNode(2)
var n3 = new TreeNode(3)
var n4 = new TreeNode(4)
var n5 = new TreeNode(5)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5

console.log(sumOfLeftLeaves(n1))