404. Sum of Left Leaves
Easy
661
75
Favorite
Share Find the sum of all left leaves in a given binary tree.
Example:
3复制代码
/
9 20 / 15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
思路:深度搜索算法,是左子树,且没有子节点,add
代码:python3
class Solution(object): def sumOfLeftLeaves(self, root): cache=[0] def dfs(root,left): if not root:return if left and not root.left and not root.right: cache[0] += root.val dfs(root.left,True) dfs(root.right,False) dfs(root,False) return cache[0]复制代码