題目連結 | 404. 左葉子之和 |
---|---|
思路 | 樹的遍歷(DFS) |
題解連結 | 官方題解 |
關鍵點 | 無 |
時間複雜度 | \(O(n)\) |
空間複雜度 | \(O(n)\) |
程式碼實現:
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
answer = 0
def dfs(node):
if node is None:
return
nonlocal answer
if node.left is not None:
if node.left.left is None and node.left.right is None:
answer += node.left.val
else:
dfs(node.left)
dfs(node.right)
dfs(root)
return answer