# 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
In the python code above, why when using function pathSum recursively, there has to be self.pathSum, but when using inner function "traverse" recursively, there is no "self." prefix before calling traverse recursively?