Find the sum of all left leaves in a given binary tree.
Example:
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Solution in python:
# 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: TreeNode) -> int:
summary = 0
def traverse(root):
if root == None:
return
else:
traverse(root.left)
if root.left != None and root.left.left == None and root.left.right == None:
nonlocal summary
summary += root.left.val
traverse(root.right)
traverse(root)
return summary
留言