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

问题描述 投票:-1回答:1

我使用递归为leetcode问题编写了代码“108. Left of Left Leaves”。它没有给我预期的结果。


# 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个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.