---
# System prepended metadata

title: 1302. Deepest Leaves Sum

---

# 1302. Deepest Leaves Sum

## 題目概要

計算二元樹的葉子節點總和。

![](https://i.imgur.com/3268Sz2.png)

## 解題技巧

- 用 DFS (深度優先搜索)法解，一層一層去算每層的總和，然後輸出最後一層結果。

## 程式碼

```javascript=
/**
 * 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) {
    let result = [];
    
    const dfs = (node, count = 0) => {
        // both count and result are 0 or empty
        if (count === result.length) {
            result[count] = node.val; // head
        } else {
            result[count] += node.val;
        }
        if (node.left)
            dfs(node.left, count + 1);
        
        if (node.right)
            dfs(node.right, count + 1);
    }
    // sum of every level
    dfs(root);
    
    return result[result.length - 1];
};
```

![](https://i.imgur.com/7YuF7QK.png)
