[路飞]_leetcode_1302.层数最深叶子节点的和

111 阅读1分钟

给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。

示例 1:

            1
           / \
          2   3
         / \    \
        4   5    6
       /          \
      7            8
输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出:15

示例 2:

输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
输出:19

解题思路

这一题我们可以通过深度优先遍历,遍历每一层的节点,然后使用一个数组记录每一层值的和,最后输出数组最后一个数也就是树的最后一层的和。

代码

var dfs = function(root, depth, arr) {
    if (!root) return
    if (arr[depth] == undefined) {
        arr[depth] = 0
    } 
    arr[depth] += root.val
    dfs(root.left, depth + 1, arr)
    dfs(root.right, depth + 1, arr)
}
var deepestLeavesSum = function(root) {
    let arr = [0]
    dfs(root, 0, arr)
    return arr[arr.length - 1]
};