- https://leetcode.com/problems/sum-of-left-leaves
- https://leetcode-cn.com/problems/sum-of-left-leaves/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
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)
class Solution:
def sumOfLeftLeaves(self, root):
if not root:
return 0
_sum = 0
stack = [root]
while stack:
root = stack.pop()
if root.left and not root.left.left and not root.left.right:
_sum += root.left.val
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
return _sum
from collections import deque
class Solution:
def sumOfLeftLeaves(self, root):
if not root:
return 0
_sum = 0
queue = deque([root])
while queue:
root = queue.popleft()
if root.left and not root.left.left and not root.left.right:
_sum += root.left.val
if root.left:
queue.append(root.left)
if root.right:
queue.append(root.right)
return _sum