计算给定二叉树的所有左叶子之和。
示例:
3 / \ 9 20 / \ 15 7 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
# 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
count = 0
stack = [root]
while stack:
node = stack.pop()
left, right = node.left, node.right
if left:
stack.append(left)
if not left.left and not left.right: count += left.val
if right: stack.append(right)
return count