Skip to content

Latest commit

 

History

History
59 lines (52 loc) · 1.37 KB

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

File metadata and controls

59 lines (52 loc) · 1.37 KB

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

/*
 * @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

解法 1: 层序遍历

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
}

Case

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)
})