1302. 层数最深叶子节点的和

131 阅读1分钟

题目描述

leetcode-cn.com/problems/de…

分析

容易想到的一个想法是 BFS 记录每层节点和,取最深一层的 value

算法

BFS

过程

使用 Map 用来记录,

通过 BFS 遍历整棵树,记录每层节点和

取 map 中最大层的 value

代码

/**
 * 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 deepestLeavesSum = function(root) {
    const map = new Map()
    
    const bfs = (root, level) => {
        if (!root) return
        const curLevel = map.get(level)
        if (!curLevel) {
            map.set(level, root.val)
        } else {
            map.set(level, curLevel + root.val)
        }
        
        bfs(root.left, level + 1)
        bfs(root.right, level + 1)
    }
    
    bfs(root, 0)
    let cnt = 0
    for (const item of map.keys()) {
        cnt = Math.max(cnt, item)
    }
    
    return map.get(cnt)
};