Python递归未给出“左叶总和”的正确结果

时间:2019-04-25 04:46:27

标签: python recursion binary-tree

我使用递归为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

1 个答案:

答案 0 :(得分:0)

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

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