# 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 pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
#ref http://bookshadow.com/weblog/2016/10/23/leetcode-path-sum-iii/
def traverse(root, sum):
"""
:rtype: int
return the number of paths connecting to root and has sum equals to sum
"""
if not root:
return 0
return (root.val==sum) + traverse(root.left, sum-root.val) + traverse(root.right, sum-root.val)
if not root:
return 0
ans = 0
ans += traverse(root, sum)
#if not start from root
ans += self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
return ans
在上面的python代码中,为什么在递归使用函数pathSum时,必须有self.pathSum,但是当使用内部函数"遍历"递归地,没有自我。"递归调用遍历之前的前缀?