# LeetCode 1302. Deepest Leaves Sum ###### tags: `python`,`LeetCode` >這邊使用Python解題 ## 題目: Given the root of a binary tree, return the sum of values of its deepest leaves. ## 範例 ### 範例 1: ![](https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png) ``` Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 ``` ### 範例 2: ``` Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19 ``` ## 條件限制 * The number of nodes in the tree is in the range [1, 104]. * 1 <= Node.val <= 100 ## 我的解題思路: 這一題蠻複雜的,需要我們去走訪一顆二元樹,那二元樹走訪主要有BFS與DFS,那我這邊為了要記錄走訪的深度所以使用BFS,資料結構選用queuq來實作,將每一層的節點val加總,並且回傳最深層的加總值 ## 程式碼: ``` def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: d = deque([root]) result = [root.val] level = 0 while(len(d)>0): level +=1 a = [] while(len(d)>0): cur = d.pop() a.extend([x for x in (cur.left, cur.right) if x != None]) if len(a)>0: result.append(sum([x.val for x in a])) d.extend(a) return result[level-1] ```