base case => node is none
recursive case => Left child is / isn't Leave
class Solution(object): def sumOfLeftLeaves(self, root): if not root: return 0 if root.left and not root.left.left and not root.left.right: return root.left.val + self.sumOfLeftLeaves(root.right) return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) # isn't leave
Could be 3 Lines, but L2 would be too long.
thanks @tototo's advise!
@YJL1228 Thanks for sharing. You can remove the 'else:' line to get a 5-line solution :) Besides, as a best practice, comparison to None should always be done with is or is not. So, if you compare root with None explicitly, we'd better write in this way 'if root is None:', or just simply 'if not root:'.
Similar, but somewhat clearer ... (probably should not indent that deep)
def sumOfLeftLeaves(self, root): def helper(node, isLeft): if node: if isLeft and not node.left and not node.right: return node.val # Only returns when isLeft and isLeaf return helper(node.left, True) + helper (node.right, False) return 0 return helper(root, False) # Seems that the OJ doesn't treat bare root as a left leaf
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.