python - Python recursion didn't give correct result for "sum of left leaves"
问题描述
I wrote a code for the leetcode problem "108. Sum of Left Leaves" using recursion. It didn't give me the expected result.
# 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
When the input is [3,9,20,null,null,15,7]
I expected a 24 to be returned, but the code only gave me 9
解决方案
您没有在根下方添加叶子的结果。你需要这个:
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
推荐阅读
- batch-file - 批处理文件检查程序打开的文件
- android - 如何在 android 设备上获取应用程序崩溃详细信息(自己的统一应用程序)
- javascript - 使用 $obj->select 对从数据库中提取的数组进行排序
- python - WSGI 文件未在 Windows Server 2012 上的 Apache 2.4 上加载 Python Flask 文件
- rxjs - 我可以取消 RxJs 延迟吗?
- android - Flutter:为什么这个类不被识别为一个类?
- bash - 使用 linux bash shell 格式化文件中的日期字符串
- framer-motion - 如何在初始加载时禁用 AnimatePresence 动画?
- android - Android App(5)将无法加载Android Library Project(2)中声明的外部依赖(1)
- for-loop - 如何创建N个嵌套for循环