728x90
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def sumOfLeftLeavesHelper(root, is_left):
if not root:
return 0
if not root.left and not root.right:
return root.val if is_left else 0
return sumOfLeftLeavesHelper(root.left, True) + sumOfLeftLeavesHelper(root.right, False)
return sumOfLeftLeavesHelper(root, False)
leaf 노드 까지 탐색한다.
left일 경우에만 +
출처: github.com/jiapengwen/LeetCode/blob/master/Python/sum-of-left-leaves.py
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Fizz Buzz 파이썬 (여러 솔루션) (0) | 2021.04.16 |
---|---|
[LeetCode] Longest Palindrome 파이썬 (bitwise &, Counter) (0) | 2021.04.16 |
[LeetCode] Is Subsequence 파이썬 (pointer, relative position) (0) | 2021.04.15 |
[LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce) (0) | 2021.04.14 |
[LeetCode] First Unique Character in a String 파이썬 (Counter, str.find) (0) | 2021.04.14 |
댓글