/*
* @lc app=leetcode.cn id=1302 lang=typescript
*
* [1302] 层数最深叶子节点的和
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function deepestLeavesSum(root: TreeNode | null): number {}
// @lc code=end
function deepestLeavesSum(root: TreeNode | null): number {
if (!root) return 0
let queue = [root]
let res = 0
while (queue.length) {
let tmp: TreeNode[] = []
res = 0
for (let node of queue) {
res += node.val
if (node.left) tmp.push(node.left)
if (node.right) tmp.push(node.right)
}
queue = tmp
}
return res
}
test.each([
{ input: { root: [1, 2, 3, 4, 5, null, 6, 7, null, null, null, null, 8] }, output: 15 },
{ input: { root: [6, 7, 8, 2, 7, 1, 3, 9, null, 1, 4, null, null, null, 5] }, output: 19 },
])('input: root = $input.root', ({ input: { root }, output }) => {
expect(deepestLeavesSum(BinaryTree.deserialize(root))).toBe(output)
})