# 資訊 :::info - Question: 404. Sum of Left Leaves - From: Leetcode Daily Challenge 2024.0414 - Difficulty: Easy ::: --- # 目錄 :::info [TOC] ::: --- # 題目 Given the `root` of a binary tree, return the sum of all left leaves. A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. > Example 1: :::success * Input: `root = [3,9,20,null,null,15,7]` * Output: 24 * Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively. ::: > Example 2: :::success * Input: root = [1] * Output: 0 ::: > Constraints: :::success * The number of nodes in the tree is in the range `[1, 1000]`. * -1000 <= `Node.val` <= 1000 ::: --- # 解法 ## 概念 這題就是簡單的 DFS 走訪過去就好,不過因為卡了一筆測資 `[1,2]` 才發現並不是所有「最後一片葉子」都不能算,而是要看是不是左邊再決定要不要算,因此這次 DFS 中多帶了一個 flag `left`,指出是不是在左邊,只有在左邊的才需要加到答案裡面 ## 程式碼 ```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 __init__(self): self.sum = 0 def dfs(self, root: TreeNode, left: bool ): if not root.left and not root.right and left == True: self.sum += root.val else: if root.left: self.dfs(root.left, True) if root.right: self.dfs(root.right, False) def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: self.dfs(root, False) return self.sum ``` --- # 複雜度 ## 時間複雜度 因為是看完整棵 tree,所以是 $O(n)$ ![TimeComplexity20240414](https://hackmd.io/_uploads/ByxvRn_eC.png =80%x) ## 空間複雜度 空間部分應該可以算 $O(1)$ ![SpaceComplexity20240414](https://hackmd.io/_uploads/SkgO02Ox0.png =80%x)