1302. 层数最深叶子节点的和
给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
function deepestLeavesSum(root: TreeNode | null): number { let res = 0 if (root === null) return res const nodeQue: TreeNode[] = [root] while(nodeQue.length) { const nodes = nodeQue.splice(0) const len = nodes.length for(let i = 0; i < len; i++) { const node = nodes[i] if (node.left) { nodeQue.push(node.left) } if (node.right) { nodeQue.push(node.right) } } if (nodeQue.length === 0) { res = nodes.reduce((pre, node) => { pre += node.val return pre }, 0) } } return res };
|