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
posted @ 2024-09-12 01:22  WrRan  阅读(3)  评论(0编辑  收藏  举报