题目描述
给你一棵二叉树,请你返回层数最深的叶子节点的和。
示例:

输入: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
输出: 15
提示:
- 树中节点数目在
1到10^4之间。 - 每个节点的值在
1到100之间。
思路
广度优先搜索。但是要注意保存最后一层节点的值。我这里使用两个队列,依次按层遍历,底层为空时,上层即为最后一层,求和即为结果。
解法
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const deepestLeavesSum = root => {
let highLevel = [];
let lowLevel = [root];
while (lowLevel.length) {
highLevel = lowLevel;
lowLevel = [];
highLevel.forEach(node => {
const { left, right } = node;
if (left) lowLevel.push(left);
if (right) lowLevel.push(right);
});
}
return highLevel.reduce((total, node) => total + node.val, 0);
};