【问题标题】:Python recursion didn't give correct result for "sum of left leaves"Python 递归没有给出“左叶总和”的正确结果
【发布时间】:2019-09-14 10:53:09
【问题描述】:

我使用递归为 leetcode 问题“108. 左叶总和”编写了一个代码。它没有给我预期的结果。


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:

            return 0

        ans = 0

        if root.left and not root.left.left and not root.left.right:

            ans += root.left.val


        self.sumOfLeftLeaves(root.left)
        self.sumOfLeftLeaves(root.right)

        return ans

当输入是 [3,9,20,null,null,15,7]

我希望返回 24,但代码只给了我 9

【问题讨论】:

    标签: python recursion binary-tree


    【解决方案1】:

    您没有在根下方添加叶子的结果。你需要这个:

    class Solution(object):
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root is None:
    
                return 0
    
            ans = 0
    
            if root.left and not root.left.left and not root.left.right:
                ans += root.left.val
    
            ans += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
    
            return ans
    

    【讨论】:

    • 感谢您的回复!您能否解释一下“ans += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)”?我注意到它没有将 .val 相加,但不是将 ans 定义为 .vals 的总和吗?
    • 如果当前节点是左叶,则需要将其值设为答案ans += root.left.val如果不是,则需要将其下左右节点下的所有左叶相加@987654323 @
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多