---
# System prepended metadata

title: '1302. [Deepest Leaves Sum](https://leetcode.com/problems/deepest-leaves-sum/)'

---

# 1302. [Deepest Leaves Sum](https://leetcode.com/problems/deepest-leaves-sum/)
<!-- https://leetcode.com/problems/deepest-leaves-sum/ -->
### 最後成功submit的code
```python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
        n_layer = 0
        result = {}
        result['max_layer'] = 0
        self.traverse(root,n_layer,result)
        return sum(result['ans'])
    def traverse(self,node,n_layer,result):
        if not node:
            return
        if not node.left and not node.right:
            if n_layer > result['max_layer']:
                result['max_layer'] = n_layer
                result['ans'] = [node.val]
            elif n_layer == result['max_layer']:
                result['ans'].append(node.val)
            else:
                return
        self.traverse(node.left,n_layer+1,result)
        self.traverse(node.right,n_layer+1,result)
        
```
有點類似113. [Path Sum II](https://leetcode.com/problems/path-sum-ii/)

只不過這次要把最深那一層leaf的值給存下來
想法是要記錄目前最深的那層(max_layer)是哪層，以及值是甚麼
如果另一個分支也走到leaf，則要判斷這個leaf的層數
1. 大於(max_layer) -> 答案的array要從這層leaf開始算起
2. 等於(max_layer) -> 同一層的leaf 答案的array加入這層的值
3. 小於(max_layer) -> 甚麼都不做

### 一開始錯誤的code
``` python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
        max_layer = 0
        n_layer = 0
        result_list = []
        self.traverse(root,n_layer,max_layer,result_list)
        return sum(result_list)
    def traverse(self,node,n_layer,max_layer,result_list):
        if not node:
            return
        if not node.left and not node.right:
            if n_layer > max_layer:
                max_layer = n_layer
                result_list.append(node.val)
            elif n_layer == max_layer:
                result_list.append(node.val)
            else:
                return
        self.traverse(node.left,n_layer+1,max_layer,result_list)
        self.traverse(node.right,n_layer+1,max_layer,result_list)
```

這樣子max_layer 無法固定被存取下來? 每一次call traverse時，max_layer傳入的都是 0 ，後來才改成存在result這個字典裡的'max_layer'