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   
最后修改日期: 2021年1月27日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。