404. 左叶子之和
题目链接 | 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