python leetcode 404. Sum of Left Leaves

二叉树就用递归 关键是如何判断左叶

class Solution:
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        res=[0]
        def help(now,parent):
            if not now.left and not now.right and now!=parent.right:
                res[0]+=now.val 
                return
            if now.left:
                help(now.left,now)
            if now.right:
                help(now.right,now)
        if not root:
            return 0 
        if root.left:
            help(root.left,root)
        if root.right:
            help(root.right,root)
        return res[0]

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/84626661